iPhone:如何在现有的词典数组中添加额外的对象和键?

时间:2011-12-16 00:33:58

标签: iphone arrays dictionary key

我有几个字典数组,包含地址和联系方式。我想遍历每个字典数组并查找每个地址的位置并存储它们相应的经度和纬度。因此,对于任何字典数组,我希望能够追加两个附加键“经度”和“纬度”与相应的值。

目前,我创建了一个新词典,读取每个键和值[包括新的经度和纬度],然后编写一个全新的数组。似乎太复杂了。还有更好的方法吗?

        //copy into new array
    [dict setObject:[[array objectAtIndex:x] objectForKey:@"Category"]      forKey:@"Category"];
    [dict setObject:[[array objectAtIndex:x] objectForKey:@"Name"]          forKey:@"Name"];
    [dict setObject:[[array objectAtIndex:x] objectForKey:@"Address"]       forKey:@"Address"];
    [dict setObject:[[array objectAtIndex:x] objectForKey:@"PhoneNumber"]   forKey:@"PhoneNumber"];
    [dict setObject:[[array objectAtIndex:x] objectForKey:@"ContactTitle"]  forKey:@"ContactTitle"];
    [dict setObject:[[array objectAtIndex:x] objectForKey:@"ContactName"]   forKey:@"ContactName"];

//APPENDING LOCATION KEYS AND DATA

    [dict setObject:[[array objectAtIndex:x] objectForKey:@"Longitude"]  forKey:@"Longitude"];
    [dict setObject:[[array objectAtIndex:x] objectForKey:@"Latitude"]       forKey:@"Latitude"];

    [masterArrayWithDistance addObject:[dict copy]]; 

2 个答案:

答案 0 :(得分:1)

一种方法:

NSMutableDictionary* d = [NSMutableDictionary dictionaryWithDictionary: dict];
[d setObject: newLongitude forKey: @"Longitude"];
[d setObject: newLatitude forKey: @"Latitude"];
[masterArrayWithDistance addObject: d]; 

另外,不知道为什么你需要首先复制字典。 addObject:只会保留一个参考。

答案 1 :(得分:1)

您想要创建数组/字典的mutableCopy。

NSMutableArray *copyArray = [originalArray mutableCopy];
NSMutableDictionary *copyDic = [[array objectAtIndex:x] mutableCopy];
[copyDic setObject:[[array objectAtIndex:x] objectForKey:@"Longitude"]  forKey:@"Longitude"];
[copyDic setObject:[[array objectAtIndex:x] objectForKey:@"Latitude"]       forKey:@"Latitude"];

然后你可以用新词典替换旧的词典/数组。