问题
I want compare 2 NSMutableArray values and check which indexPath is different and store this numbers of index in one array. for example I have these NSMutableArray :
NSMutableArray *a = [[NSMutableArray alloc]initWithObjects:@"1",@"2",@"3",@"4",@"5",@"6", nil];
NSMutableArray *b = [[NSMutableArray alloc]initWithObjects:@"11",@"2",@"5",@"3",@"53",@"6", nil];
and I want to compare these two NSMutableArray index to index (compare value to value) and tell me that which index of array in these NSMutableArrays is different. for example in two NSMutableArray on top this index is different (0,2,3,4) and I want store this values in certain Array.
回答1:
NSMutableArray* differentIndex;
differentIndex = [[NSMutableArray alloc] init];
for(int i = 0 ; i < [a count]; i++) {
if(i < [b count]){
if(![b[i] isEqual:a[i]]){
[differentIndex addObject:[NSNumber numberWithInt:i]];
}
} else {
[differentIndex addObject:[NSNumber numberWithInt:i]];
}
}
Now your differentIndex contains all the different index in the arrays. :)
回答2:
NSMutableArray *a = [[NSMutableArray alloc]initWithObjects:@"1",@"2",@"3",@"4",@"5",@"6", nil];
NSMutableArray *b = [[NSMutableArray alloc]initWithObjects:@"11",@"2",@"5",@"3",@"53",@"6", nil];
NSMutableArray *new = [[NSMutableArray alloc]init];
for(int i =0;i<[b count]<=[a count]?[b count]:[a count];i++)
{
NSString *_keyA = [a objectAtIndex:i];
NSString *_keyB = [b objectAtIndex:i];
if ([_keyA isEqualToString:_keyB])
continue;
[new addObject:[NSString stringWithFormat:@"%d",i]];
}
来源:https://stackoverflow.com/questions/16814774/how-to-compare-2-nsmutablearray-and-get-different-number-of-value