Search code examples
objective-ccocoacocoa-touchnsarraysubtraction

Subtract objects in one NSArray from another array


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?


Solution

  • Something like this?

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