NSMutableArray:如何允许重复值

时间:2011-12-29 10:54:41

标签: iphone objective-c

我正在阅读JSON代码,例如:

[{"question_id":"1",
  "trigger_value":"Yes",
  "question_text":"What is your first    name?",
  "question_type":"YN"},    
 {"question_id":"2",
  "trigger_value":"Yes",
  "question_text":"What is your second name?",
  "question_type":"YN"}
]

但是一旦将其设置为NSMutableArray,就会删除重复的值。我想让他们检查每个问题的问题类型。

  NSString *question_id;
  NSString *question_text;
  NSString *question_type;

   while (dicjson = (NSDictionary*)[enumerator nextObject]) {
      question_id = [dicjson objectForKey:@"question_id"];        
     question_type = [dicjson objectForKey:@"question_type"];

     [mutjson setObject:question_id    forKey:question_type];
}    

您能否告诉我允许重复值...? 提前谢谢。

3 个答案:

答案 0 :(得分:3)

mutjson看起来像一个可变字典而不是一个可变数组。

所以是的,如果你设置相同的键,在字典对象中,它将覆盖以前的值。 如果你需要存储字典对象,创建一个可变数组并将该数组中的每个对象添加为一个自由对象......

NSMutableArray *results = [[NSMutableArray alloc] init];

while (dicjson = (NSDictionary*)[enumerator nextObject]) {
     question_id = [dicjson objectForKey:@"question_id"];        
     question_type = [dicjson objectForKey:@"question_type"];
     [result addObject:[NSDictionary dictionaryWithObject:question_id forKey:question_type]];
}

答案 1 :(得分:1)

你不能在NSMutableArray中setObject:forKey:。您必须使用addObject:。它也更容易创建这样的数组:

NSArray *values = [jsonDict allValues];

答案 2 :(得分:1)

你正在混淆字典的数组。数组可以包含重复值。字典不能容纳重复的密钥。

JSON响应是一个字典数组。您编写代码的方式,特别是[mutjson setObject:question_id forKey:question_type];似乎表明您只是使用字典。

如果您想检查每个问题的问题类型,请尝试改为:

NSString *question_type;

for (NSMutableDictionary *dict in dicjson) {
    // I would suggest renaming dicjson to something more descriptive, like results
    question_type = [dict objectForKey: @"question_type"];

    // Do what you would like now that you know the type
}