我有一个NSMutableArray
和一个NSArray
。两者都由NSDictionarys
本身的元素组成。两者的示例结构如下:
NSMutableArray
[
{
objectId = 4274;
name = orange;
price = 45;
status = approved;
},
{
objectId = 9035;
name = apple;
price = 56;
status = approved;
},
{
objectId = 7336;
name = banana;
price = 48;
status = approved;
}
.
.
.
.
]
NSAraay 是
NSArray
[
{
objectId = 4274;
name = orange;
price = 106;
status = not_approved;
},
{
objectId = 5503;
name = apple;
price = 56;
status = approved;
}
]
我想要的是合并这两个数组,这样,如果 in 中的任何元素与 in中的任何元素NSArray
相同,则 element in应该覆盖在 element in 上。objectId
NSMutableArray
NSArray
NSMutableArray
所以在这种情况下,最终合并的数组应该是这样的
MergedArray
[
{
objectId = 4274;
name = orange;
price = 106;
status = not_approved;
},
{
objectId = 9035;
name = apple;
price = 56;
status = approved;
},
{
objectId = 7336;
name = banana;
price = 48;
status = approved;
},
{
objectId = 5503;
name = apple;
price = 56;
status = approved;
}
.
.
.
.
]
我知道的唯一方法是遍历两个数组并合并。有没有更好的办法?任何帮助将不胜感激。
编辑:
按照 dasblinkenlights 的建议,我按照以下方式进行了操作
-(NSMutableArray*)mergeTwoArray:(NSArray*)array1 :(NSArray*)array2
{
//array1 will overwrite on array2
NSSet* parentSet = [NSSet setWithArray:array2];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
for (NSDictionary *item in parentSet)
[dict setObject: item forKey: [item objectForKey:@"objectId"]];
NSLog(@"initial dictionary is %@",dict);
for (NSDictionary *item in array1)
[dict setObject: item forKey: [item objectForKey:@"objectId"]];
NSLog(@"final dictionary is %@ with all values %@", dict,[dict allValues]);
return [NSMutableArray arrayWithArray:[dict allValues]];
}