Unrecognized selector error when indexing into a dictionary of arrays

半世苍凉 提交于 2019-12-02 10:17:47

问题


I have a dictionary of arrays that is causing __NSCFDictionary objectAtIndex: errors.

Can someone tell me why? The dictionary clearly has at least 1 array at the time of the error.

 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:


In your case [[json objectForKey:@"words"] objectForKey:@"word"]; is returning a dictionary and not an array. Try doing the following,

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);
}

Your response string also shows that value for word is,

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

which is a dictionary with key value pairs as rowsreturned:0, id:-1 etc..



来源:https://stackoverflow.com/questions/13464433/unrecognized-selector-error-when-indexing-into-a-dictionary-of-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!