有没有办法在目标c中合并两个NSMutableArray?

时间:2010-10-02 12:43:06

标签: objective-c

我有两个NSMutableArray填充了数据对象。如果发现任何更改,如何比较数组和合并。

例如: 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'}

结果是: Array= index(0) userName = {'a',1,'address'}      index (1) userName = {'b',2,'address'}           index(2) userName = {'c',3,'address'}

请帮忙

2 个答案:

答案 0 :(得分:51)

一种简单的方法是使用集合:

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

NSArray *array = [set allObjects];

虽然您之后必须自己排序array

(N.B。,我通常习惯使用变量的小写名称。)

答案 1 :(得分:11)

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];
  }