【问题标题】:Only the last value of NSMutableDictionary is added to NSMutableArray只有 NSMutableDictionary 的最后一个值被添加到 NSMutableArray
【发布时间】:2013-08-05 06:33:57
【问题描述】:

我已尽力寻找将 NSMutableDictionary 添加到 NSMutableArray 的答案。不幸的是,他们都要求我使用“[allValues]”,这不是我想要的。

问题来了,

在头文件中,我定义了,

NSMutableArray *arData;

而在m文件中,

arData = [[NSMutableArray alloc] init];

NSMutableDictionary *mutableDictionary5 = [[NSMutableDictionary alloc]init];

for (i=0;i<[[[self rssParser]rssItems]count];i++)
{

    Lat = [[[[[self rssParser]rssItems]objectAtIndex:i]lat] doubleValue];
    Lng = [[[[[self rssParser]rssItems]objectAtIndex:i]lng] doubleValue];
    // Creates a marker in the center of the map.
    GMSMarker *marker = [[GMSMarker alloc] init];
    marker.position = CLLocationCoordinate2DMake(Lat, Lng);
    marker.title = [[[[self rssParser]rssItems]objectAtIndex:i]header];

[mutableDictionary5 setObject:marker.title forKey:@"title"];

[arData setValue:[mutableDictionary5 valueForKey:@"title"] forKey:@"title"];
}

“arData”仅获得 [[[[self rssParser]rssItems]objectAtIndex:i]header] 的最后一个值。而且我确信 mutableDictionary5 获得了所有值,因为我在代码末尾添加了以下内容,

 NSLog(@"mutableDictionary5 values=%@",[mutableDictionary5 allValues]);

它打印标题的所有值。

我知道它不应该是 setvalue,但是,我尝试使用 [mutableDictionary5 allValues]、“addobjects”、“allkeys”。他们不工作。我应该怎么做才能让 NSMutableArray arData 以“title”为键添加所有 title 值?谢谢。

对不起,我的英语不好,不是我的母语。

【问题讨论】:

  • 简单地使用[arData addObject:[mutableDictionary5 objectForKey:@"title"]];有什么问题
  • 它给出字符串响应,并在使用 objectforkey 传递数据时给出错误

标签: iphone nsmutablearray nsmutabledictionary object-code


【解决方案1】:

您错误地使用setValue 而不是addObject

[arData addObject:mutableDictionary5]; 

如果你在循环分配一个新字典,这将起作用。
如果您想将数组缩减为仅标题,请在 循环之后执行此操作:

NSArray *titleArray = [arData valueForKeyPath:@"title"]; 

现在你有了一个只包含标题的数组。

顺便说一句,您可以努力发明更好的变量名称。请注意,按照惯例,Objective-C 变量名以小写字母开头,而类名大写。

【讨论】:

  • 我想我需要为此创建多个 nsmutabledictionary。非常感谢。现在可以了!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多