我有NSMutableArray
NSDictionary
这样的内容:
myArray (
{
chatins = 20;
placeImageString = 244211112265925;
},
{
chatins = 5;
placeImageString = 154909144575109;
},
{
chatins = 30;
placeImageString = 193867280641162;
},
{
chatins = 13;
placeImageString = 224627130902;
},
)
和NSMutableArray
的另一个NSDictionary
是这样的:
myArray2
(
{
category = "Local business";
distance = "0.1";
name = "Mts India";
placeImageString = 244211112265925;
},
{
category = "Local business";
distance = "0.17";
name = "Aegis Ltd";
placeImageString = 154909144575109;
},
{
category = "Automobiles and parts";
distance = "0.19";
name = Autopsyche;
placeImageString = 78480207511;
},
{
category = Company;
distance = "0.19";
name = "The Oberoi, Gurgaon";
placeImageString = 121676041233945;
},
)
我想合并myArray
和myArray2
,以获得NSMutableArray
NSDictionary
placeImageString
的结果,如下所示我的myArray2
是匹配的关键字两个字典数组中的数据,如果在chatins
中找不到密钥,则myArray3
(
{
category = "Local business";
distance = "0.1";
name = "Mts India";
placeImageString = 244211112265925;
chatins = 20;
},
{
category = "Local business";
distance = "0.17";
name = "Aegis Ltd";
placeImageString = 154909144575109;
chatins = 5;
},
{
category = "Automobiles and parts";
distance = "0.19";
name = Autopsyche;
placeImageString = 78480207511;
chatins = 0;
},
{
category = Company;
distance = "0.19";
name = "The Oberoi, Gurgaon";
placeImageString = 121676041233945;
chatins = 0;
},
)
密钥的值应为0。
{{1}}
答案 0 :(得分:2)
这里我有一个示例代码:
NSMutableArray *array1 = [[NSMutableArray alloc] init];
NSMutableArray *array2 = [[NSMutableArray alloc] init];
NSMutableDictionary * dict = [[NSMutableDictionary alloc]
initWithObjects:[NSArray arrayWithObjects:@"1",@"ABC", nil]
forKeys:[NSArray arrayWithObjects:@"ID",@"NAME", nil]];
[array1 addObject:dict];
dict = nil;
/*
Same way added 2 more dictionaries to the same array - array1
*/
NSLog(@"array1: %@", array1);
dict = nil;
dict = [[NSMutableDictionary alloc]
initWithObjects:[NSArray arrayWithObjects:@"1",@"DEF", nil]
forKeys:[NSArray arrayWithObjects:@"ID",@"ADDRESS", nil]];
[array2 addObject:dict];
dict = nil;
/*
Same way added 2 more dictionaries to the same array - array2
*/
NSLog(@"array2: %@", array2);
for (int index = 0; index < [array1 count]; index ++) {
NSMutableDictionary *dict1 = [array1 objectAtIndex:index];
for (NSMutableDictionary *dict2 in array2) {
if ([[dict1 objectForKey:@"ID"] isEqualToString:
[dict2 objectForKey:@"ID"]]) {
[dict1 setObject:[dict2 objectForKey:@"ADDRESS"] forKey:@"ADDRESS"];
}
}
}
现在最后如果您使用 array1 进行检查,则在所有这些字典中还会添加一个密钥( ADDRESS )。
希望得到这个帮助。
-Mrunal
答案 1 :(得分:0)
1. Create a new empty NSMutableArray newArray
2. Loop through all NSDictionaries of myArray2
a. Copy the current NSDictionary to a new NSMutableDictionary newDict
b. Loop through myArray1
b1. if myArray1.dict.placeImageString == newDict.placeImageString
- Add myArray1.dict.chatins to newDict
- break out of loop
c. add newDict to newArray