索引到数组字典时出现无法识别的选择器错误
Posted
技术标签:
【中文标题】索引到数组字典时出现无法识别的选择器错误【英文标题】:Unrecognized selector error when indexing into a dictionary of arrays 【发布时间】:2012-11-19 23:43:57 【问题描述】:我有一个导致__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];
【问题讨论】:
[[json objectForKey:@"words"] objectForKey:@"word"];正在返回字典而不是数组。尝试在该行之后添加一个 NSLog。你可以看到它 【参考方案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:0
、id:-1
等的字典。
【讨论】:
以上是关于索引到数组字典时出现无法识别的选择器错误的主要内容,如果未能解决你的问题,请参考以下文章
从字典访问 FlutterStandardTypedData 时出现“[__NSArrayI 数据]:无法识别的选择器”
尝试获取 AppDelegate 时出现“无法识别的选择器发送到实例”错误
使用 UIImageWriteToSavedPhotosAlbum 保存图像时出现无法识别的选择器错误