索引到数组字典时无法识别选择器错误

时间:2012-11-19 23:43:57

标签: objective-c ios json nsdictionary

我有一个导致__NSCFDictionary objectAtIndex:错误的数组字典。

有人可以告诉我为什么吗?字典显然在错误发生时至少有一个数组。

 NSError *error;
 responseString = [[NSString alloc] initWithData:self.responseData2 encoding:NSUTF8StringEncoding];

/* response string contains this:
   {"words":
     {
    "word": {"rowsreturned":0,"id":"-1","date":"","word":"","term":"","definition":"","updated_on":""}
     },
    "status":"",
    "rowsreturned":""
  }
*/

 NSDictionary *json = [NSJSONSerialization JSONObjectWithData:self.responseData2 options:kNilOptions error:&error];

 NSArray *todaysWord = [[json objectForKey:@"words"] objectForKey:@"word"];

 //error here -[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance
 NSDictionary *word = [todaysWord objectAtIndex:0];

1 个答案:

答案 0 :(得分:1)

在你的情况下[[json objectForKey:@"words"] objectForKey:@"word"];正在返回一个字典,而不是一个数组。尝试执行以下操作,

id wordParam = [[json objectForKey:@"words"] objectForKey:@"word"];

if ([wordParam isKindOfClass:[NSArray class]]) {
  NSDictionary *word = [(NSArray *)wordParam objectAtIndex:0];
} else if ([wordParam isKindOfClass:[NSDictionary class]]) {
  NSDictionary *word = (NSDictionary *)wordParam;
} else {
  NSLog(@"error. %@ is not an array or dictionary", wordParam);
}

您的回复字符串还会显示word的值为

{"rowsreturned":0,"id":"-1","date":"","word":"","term":"","definition":"","updated_on":""}

这是一个字典,键值对为rowsreturned:0id:-1等。