如何获取所有NSArray中存在的对象

时间:2016-02-23 07:16:53

标签: ios objective-c nsarray

我有多个数组,例如:

NSArray *a = @[@"a", @"b", @"c"];
NSArray *b = @[@"d", @"a", @"e"];
NSArray *c = @[@"i", @"f", @"a"];

正如您所见,数组a,b,c中存在“a”。我想创建一个函数,在提供的数组中返回相同的objet。所以,就像这个,我想从他们那里得到这个“a”。如果所有数组都没有相同的对象,则返回nil。例如,“f”仅存在于c中,因此该函数应返回nil。

3 个答案:

答案 0 :(得分:2)

NSMutableSet *set = [NSMutableSet new];
NSMutableSet *set1 = [NSMutableSet setWithArray:a];
NSMutableSet *set2 = [NSMutableSet setWithArray:b];
NSMutableSet *set3 = [NSMutableSet setWithArray:c];


set = [set1 intersectSet:set2];
set = [set intersectSet:set3];

NSArray *allArray = [set allObjects];

答案 1 :(得分:1)

NSMutableSet *intersection = [NSMutableSet setWithArray:a];
[intersection intersectSet:[NSSet setWithArray:b]];
[intersection intersectSet:[NSSet setWithArray:c]];

NSArray *intersecArray = [intersection allObjects];
这项工作!从你的代码中返回一个结果数组

答案 2 :(得分:0)

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSArray *a = @[@"a", @"b", @"c"];
    NSArray *b = @[@"d", @"a", @"e"];
    NSArray *c = @[@"i", @"f", @"a"];

    NSArray *arraydOfAll=[NSArray arrayWithObjects:a,b,c,nil];
    NSArray *commonObjArray=[self intersectArray:arraydOfAll];
}



-(NSArray *)intersectArray:(NSArray *)allArray{
  NSMutableSet *set1 = [NSSet setWithArray:[allArray objectAtIndex:0]];
  for (NSInteger i=1;i<allArray.count : i++){
        [set1 intersectSet:[NSSet setWithArray:[allArray objectAtIndex:i]];
  }
  return  [set1 allObjects]
}