views:

88

answers:

1

How can I take two NSArrays, compare them, then return the number of differences, preferably the number of different objects, for example:

Array 1: one two three

Array 2: two four one

I would like that to return "1"

+1  A: 

You can do this by using an intermediate NSMutableArray:

NSArray *array1 = [NSArray arrayWithObjects:@"One", @"Two", @"Three", nil];
NSArray *array2 = [NSArray arrayWithObjects:@"Two", @"Four", @"One", nil];
NSMutableArray *intermediate = [NSMutableArray arrayWithArray:array1];
[intermediate removeObjectsInArray:array2];
NSUInteger difference = [intermediate count];

With that way, only common elements will be removed.

Laurent Etiemble
Works perfectly! Thanks a bunch!
Matt S.
If you have a relatively large # of items in the array this *might* be slow. Maybe. Measure it. If it is, considering using `NSSet` instead.
bbum