【问题标题】:iPhone: How to add extra objects and keys to existing array of dictionaries?iPhone:如何向现有的字典数组添加额外的对象和键?
【发布时间】:2012-01-21 15:28:22
【问题描述】:

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

目前,我创建了一个新字典,读取每个键和值 [包括新的经度和纬度],然后编写一个全新的数组。好像太绕了。有没有更好的办法?

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

【问题讨论】:

  • 也许更好的主意是使用一个临时的myObject = [array objectAtIndex:x] 而不是为每个键访问一次数组?
  • 或临时 NSMutableDictionary *myDict = [NSDictionary dictionaryWithDictionary:[array objectAtIndex:x]]; 并将新对象添加到其中并将其插入主对象

标签: iphone arrays dictionary key


【解决方案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"];

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

【讨论】:

    【解决方案2】:

    一种方法:

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

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

    【讨论】:

      猜你喜欢
      • 2021-10-26
      • 1970-01-01
      • 2017-02-08
      • 1970-01-01
      • 2010-12-18
      • 1970-01-01
      • 2021-06-03
      • 1970-01-01
      • 2023-02-22
      相关资源
      最近更新 更多