20

I have two NSMutableArray filled with data object. how do I compare both array and merge if any change found.

ex: Array1= index(0) userName = {'a',1,'address'} index(1) userName = {'b',2,'address'}

Array2= index(0) userName = {'c',3,'address'} index (1) userName = {'b',2,'address'}

Result is: Array= index(0) userName = {'a',1,'address'} index (1) userName = {'b',2,'address'} index(2) userName = {'c',3,'address'}

Please help

iPhoneDev
  • 2,995
  • 4
  • 33
  • 44

2 Answers2

52

An easy way is to use sets:

NSMutableSet *set = [NSMutableSet setWithArray:array1];
[set addObjectsFromArray:array2];

NSArray *array = [set allObjects];

Though you will have to sort array yourself afterward.

(N.B., I used lowercase names for the variables as is usually customary).

Wevah
  • 28,182
  • 7
  • 83
  • 72
  • This solution doesn't return unique array for custom objects. Any clue on how to get that to work? – Vibhor Goyal Oct 05 '11 at 23:13
  • 1
    Answer to my own question above: I missed creating isEqual methods for my custom classes. Here's how I did it: http://stackoverflow.com/q/254281/127036 – Vibhor Goyal Oct 05 '11 at 23:40
12
NSArray *array1, *array2;

...

MSMutableArray *result = [array1 mutableCopy];
for (id object in array2)
  {
  [result removeObject:object];  // make sure you don't add it if it's already there.
  [result addObject:object];
  }
NSResponder
  • 16,861
  • 7
  • 32
  • 46