1

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

有人能告诉我为什么吗?发生错误时,字典显然至少有 1 个数组。

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

1 回答 1

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等等。

于 2012-11-19T23:53:24.783 回答