应用程序在第二次运行nsnull计数循环时崩溃

我有一个循环,第一次工作正常,但第二次通过循环我得到:

-[NSNull count]: unrecognized selector sent to instance 0x3a094a70 *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSNull count]: unrecognized selector sent to instance 0x3a094a70' 

这是我的代码中我知道崩溃的部分(最后一行):

 ... NSLog(@"dict::%@",dictForPost); // collect the photo urls in an array photosInDict = [NSArray array]; // photos is an array of dictionaries in the dictionary photosInDict = dictForPost[@"photos"]; if (photosInDict.count) { .... 

我知道,当photosInDict没有在dic中的图片时它会崩溃,但我不知道为什么因为我在它上面启动了数组。

  photosInDict = dictForPost[@"photos"] 

替换先前分配并存储在photosInDict的对象。 因此,之前分配数组没有意义。 只是

 NSArray * photosInDict = dictForPost[@"photos"]; 

然后检查

 if ([photosInDict isKindOfClass:[NSArray class]]) { // Yes, it is an array. Do something with it. if ([photosInDict count]) { ... } } 

dictForPost[@"photos"];的结果dictForPost[@"photos"]; 给你一个NSNull对象,而不是一个数组。

一种选择是:

 NSLog(@"dict::%@",dictForPost); // collect the photo urls in an array // photos is an array of dictionaries in the dictionary photosInDict = dictForPost[@"photos"]; if ([photosInDict isKindOfClass:[NSArray class]] && photosInDict.count) { 

这条线:

 photosInDict = [NSArray array]; 

没有意义,应该删除。

你用一个空数组初始化photosInDict ,然后你用字典的“照片”值覆盖它,这恰好是NSNull 。 您需要检查为什么您的字典没有该键的数组。

如果值可以是NSNull具体取决于具体情况,则在尝试计数或采取其他操作之前,必须检查它是否为数组。