我有一個NSMutableArray
和一個NSArray
。兩者都由NSDictionarys
本身組成。 兩個樣本結構如下:根據字典中的參數合併兩個由字典組成的NSArrays
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;
}
]
我想是合併這兩個數組,這樣,如果在NSArray
任一元素的任何元素相同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]];
}
#9035在您的合併數組中出現兩次。那是故意的嗎? – 2012-04-05 14:48:03
不.. ..!我將編輯問題。感謝您指出 – chatur 2012-04-05 14:52:48