2014-01-07 80 views
0

我有一個循環,工作正常,第一次通過,但通過第二次循環時,我得到:應用程序通過循環與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崩潰,但我不明白爲什麼,因爲我開始它上面的陣列。

回答

4
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]) { 
     ... 
    } 
} 
4

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]; 

是毫無意義的,應予刪除。

+0

我認爲,因爲它是在if語句的條件下崩潰,我需要保護if以及Martin R如何顯示。除非if語句在第一個條件不滿足時退出? – BluGeni

+1

我的'if'語句可以正常工作。如果上半場是假的,下半場將不會被評估。這被稱爲短路評估,所有基於C語言(以及其他許多語言)都使用它。 – rmaddy

+0

哦,我不知道,謝謝你教我。 – BluGeni

0

您用空數組初始化photosInDict,但隨後用字典的「照片」值覆蓋它,該值恰好爲NSNull。你需要檢查你的字典爲什麼沒有這個鍵的數組。

如果根據具體情況取值爲NSNull,則在嘗試計數或執行其他操作之前,必須檢查它是否爲數組。

+0

不,「照片」的值不是「空」。它實際上有一個值,它的值是一個'NSNull'對象。 – rmaddy

+0

是不是'null'等於'[NSNull null]'? 'NSNull'是類,而'null'是實例,對嗎? 但的確,錯誤消息說'NSNull'。 – Guilherme

+2

只是說'null'很模糊。對'[NSNull null]'的調用返回一個'NSNull'實例,而不是'null'。 – rmaddy

相關問題