How can I compare two NSArray
s 开发者_开发百科and put equal objects into a new array?
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
Answer:
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
Objects will be compared using method compare:
. If you want to use another method, then just replace if (firstEl == secondEl)
with yourComparator that will return YES to equal objects: if ([firstEl yourComparator:secondEl])
//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
Finding Intersection of NSMutableArrays
精彩评论