Comparing NSMutableArray Elements for Values
I am looking for a way to compare the contents of two NSMutableArray objects. Both arrays are filled with NSMutableDictionaries which were allocated separately but occasionally contain the same data.
Simplified Example:
NSMutableArray *firstArray = [[NSMutableArray alloc] init];
NSMutableArray *secondArray = [[NSMutableArray alloc] init];
NSMutableDictionary *a = [[NSDictionary alloc] init];
[a set开发者_StackOverflow社区Object:@"foo" forKey:"name"];
[a setObject:[NSNumber numberWithInt:1] forKey:"number"];
NSMutableDictionary *b = [[NSDictionary alloc] init];
[b setObject:@"bar" forKey:"name"];
[b setObject:[NSNumber numberWithInt:2] forKey:"number"];
NSMutableDictionary *c = [[NSDictionary alloc] init];
[c setObject:@"foo" forKey:"name"];
[c setObject:[NSNumber numberWithInt:1] forKey:"number"];
[firstArray addObject:a];
[firstArray addObject:b];
[secondArray addObject:c];
a, b and c are distinct object, but the contents of a and c match.
What I am looking for is a function / approach to compare firstArray and secondArray and return only b.
In Pseudocode:
NSArray *difference = [self magicFunctionWithArray:firstArray andArray:secondArray];
NSLog(@"%@",difference)
=> ({name="bar"; number=2})
Thank you in advance.
This can be achieved using NSMutableSet
instances.
NSMutableSet * firstSet = [NSMutableSet setWithArray:firstArray];
NSMutableSet * secondSet = [NSMutableSet setWithArray:firstArray];
[firstSet unionSet:[NSSet setWithArray:secondArray]];
[secondSet intersectSet:[NSSet setWithArray:secondArray]];
[firstSet minusSet:secondSet];
NSLog(@"%@", firstSet);
精彩评论