0x90
0x90

Reputation: 6279

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 setObject:@"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.

Upvotes: 3

Views: 2884

Answers (1)

Deepak Danduprolu
Deepak Danduprolu

Reputation: 44633

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);

Upvotes: 6

Related Questions