Subtract objects in one NSArray from another array

Jacksonkr picture Jacksonkr · May 6, 2012 · Viewed 9.4k times · Source

I have two NSArrays:

NSArray *wants = [NSArray arrayWithObjects:
                  @"apples", 
                  @"oranges", 
                  @"pineapple", 
                  @"mango", 
                  @"strawberries", 
                  nil];
NSArray *needs = [NSArray arrayWithObjects:
                  @"apples", 
                  @"pineapple", 
                  @"strawberries", 
                  nil];

And I want to XOR them. Something like wants - needs so that what I have left is

[NSArray arrayWithObjects:
@"oranges", 
@"mango", 
nil];

I would normally go through some heavy looping, but I am sure there is a more practical way. What should I do instead?

Answer

Kirby Todd picture Kirby Todd · May 6, 2012

Something like this?

NSMutableArray *array = [NSMutableArray arrayWithArray:wants];
[array removeObjectsInArray:needs];