目标的替代方法为retainAll

时间:2011-11-17 19:19:34

标签: objective-c

RetainAll方法函数在java中是Objective-C中的替代方法

java中的示例代码

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MainClass {
  public static void main(String args[]) {
    String orig[] = { "1st", "2nd", "3rd", "4th", "5th", "1st", "2nd", "3rd",
        "4th", "5th" };
    String act[] = { "2nd", "3rd", "6th" };
    List origList = new ArrayList(Arrays.asList(orig));
    List actList = Arrays.asList(act);

    System.out.println(origList.retainAll(actList));
    System.out.println(origList);
  }
}

第二名第3名第2名第3名的输出

2 个答案:

答案 0 :(得分:2)

在NSArray中没有一个简单的方法,但你可以用谓词实现相同的效果:

NSArray *intersectionOfArrays = [orig filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF IN %@", act]];

正如Tim Dean所指出的,这通常是对集合而不是数组的操作,而NSSet确实有这样做的方法。如果你的应用程序实际上可以在这里使用一个集合,那么这可能是最好的方法,而不是将设置行为设置为数组。但是如果你需要保持原始顺序,你必须使用谓词。

答案 1 :(得分:1)

您应该可以使用Objective-C中的集合执行类似的操作:

NSArray *init = [NSArray arrayWithObjects:@"1st", @"2nd", @"3rd", @"4th", @"5th", @"1st", @"2nd", @"3rd", @"4th", @"5th", nil];
NSArray *act = [NSArray arrayWithObjects:@"2nd", @"3rd", @"6th", nil];

NSCountedSet *initSet = [[NSCountedSet alloc] initWithArray:init];
NSCountedSet *actSet = [[NSCountedSet alloc] initWithArray:act];

[initSet intersectSet:actSet];
NSLog(@"Intersection of sets: %@", initSet);
相关问题