Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to merge two NSMutableArray in objective c?

Tags:

objective-c

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

like image 206
iPhoneDev Avatar asked Oct 02 '10 12:10

iPhoneDev


2 Answers

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).

like image 147
Wevah Avatar answered Oct 16 '22 17:10

Wevah


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];
  }
like image 39
NSResponder Avatar answered Oct 16 '22 18:10

NSResponder