如何比较两个NSArray
并将相等的对象放入新数组?
答案 0 :(得分:6)
NSArray *array1 = [[NSArray alloc] initWithObjects:@"a",@"b",@"c",nil];
NSArray *array2 = [[NSArray alloc] initWithObjects:@"a",@"d",@"c",nil];
NSMutableArray *ary_result = [[NSMutableArray alloc] init];
for(int i = 0;i<[array1 count];i++)
{
for(int j= 0;j<[array2 count];j++)
{
if([[array1 objectAtIndex:i] isEqualToString:[array2 objectAtIndex:j]])
{
[ary_result addObject:[array1 objectAtIndex:i]];
break;
}
}
}
NSLog(@"%@",ary_result);//it will print a,c
答案 1 :(得分:2)
答案:
NSArray *firstArr, *secondArr;
// init arrays here
NSMutableArray *intersection = [NSMutableArray array];
for (id firstEl in firstArr)
{
for (id secondEl in secondArr)
{
if (firstEl == secondEl) [intersection addObject:secondEl];
}
}
// intersection contains equal objects
将使用方法compare:
比较对象。如果您想使用其他方法,只需将if (firstEl == secondEl)
替换为 yourComparator ,它将向相同的对象返回YES:if ([firstEl yourComparator:secondEl])
答案 2 :(得分:1)
//i assume u have first and second array with objects
//NSMutableArray *first = [ [ NSMutableArray alloc]init];
//NSMutableArray *second = [ [ NSMutableArray alloc]init];
NSMutableArray *third = [ [ NSMutableArray alloc]init];
for (id obj in first) {
if ([second containsObject:obj] ) {
[third addObject:obj];
}
}
NSLog(@"third is : %@ \n\n",third);
more over if u have strings in both array then look at this answer of mine