3

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.

2
  • Did you mean for secondArray to have a and b in it as well? Because right now it's just empty and I'm not sure why the second element is special. Commented Jun 14, 2011 at 17:59
  • Thanks for pointing that out. secondArray was meant to contain c. Fixed the code sample to reflect this. Commented Jun 14, 2011 at 18:18

1 Answer 1

6

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.