繁体   English   中英

为什么在NSDictionary上调用-allValues会抛出异常?

[英]Why does calling -allValues on an NSDictionary throw an exception?

我尝试从nsdictionary获取所有值,但它在第二行引发异常

NSDictionary* thetimeLineDict = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&jsonParsingError];
NSArray* theallTweets = [thetimeLineDict allValues];

以下是控制台的例外情况

2011-11-27 14:56:38.156 SparkTweet[2066:1390b] -[__NSCFArray allValues]: unrecognized selector sent to instance 0x8128310
2011-11-27 14:56:38.158 SparkTweet[2066:1390b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFArray allValues]: unrecognized selector sent to instance 0x8128310'
*** First throw call stack:
(0x14c0052 0x189cd0a 0x14c1ced 0x1426f00 0x1426ce2 0x2c48 0x33306 0x1b38445 0x1b39ecf 0x1b39d28 0x1b394af 0x9b632b24 0x9b6346fe)
terminate called throwing an exception

为什么会发生这种情况?

因为allValues不是NSArray的有效方法,而是返回的方法。

JSON解析器并不总是将字典作为最外面的Objective-C对象返回。 相反,你得到的东西取决于输入的JSON文本,并且输入的JSON文本有一个数组( [] )作为最外层的结构。

(请注意,作为一般规则,您应始终测试JSON解析器的结果以查看返回的类型,除非您绝对确定它始终是数组,或者“object”/ dictionary。)。

您正在阅读的JSON包含一个数组而不是NSDictionary,您可以在执行数据解析后通过调用以下内容来测试它:

NSLog(@"The class is %@",[thetimeLineDict class]);

输出可能是:

2011-11-27 14:56:38.156 SparkTweet[2066:1390b]:The class is NSArray

问题可能是你有一个字典数组而不仅仅是字典。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM