我尝试从nsdictionary中获取所有值,但它在第二行抛出异常
NSDictionary* thetimeLineDict = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&jsonParsingError];
NSArray* theallTweets = [thetimeLineDict allValues];
下面的是来自console
的异常。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解析器的结果,以查看返回的类型,除非您绝对确定它将始终是数组或"对象"/字典。)
您正在读取的JSON包含Array而不是NSDictionary,您可以通过在进行数据解析后调用以下代码来测试:
NSLog(@"The class is %@",[thetimeLineDict class]);
输出可能是:
2011-11-27 14:56:38.156 SparkTweet[2066:1390b]:The class is NSArray
问题可能是你有一个字典数组,而不仅仅是一个字典。