索引到数组字典时无法识别选择器错误
我有一个数组字典导致__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];
在你的情况下[[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:0
, id:-1
等。