2013-11-20 17 views
0

這可能是一個相當基本的問題,但嘗試我可能找不到導致它的原因。NSNumber numberWithInt結果NSNictionary時作爲對象添加NSNull

我寫了下面的代碼:

NSMutableDictionary * myDictionary = [[NSMutableDictionary alloc] init]; 
    NSMutableArray * values = [[NSMutableArray alloc] init]; 

    for (int i=0; i<10; i++) { 

     // create an object that can become a key in an NSDictionary 
     CustomObjectAdoptingNSCopy * someKey = [[CustomObjectAdoptingNSCopy alloc] init]; 

     // create a random value that will become an object for myDictionary ... 
     int someValue = rand()%10; 

     // ... and which also gets to be an object in the values array, provided it isn't already stored there 
     if ([values indexOfObject:[NSNumber numberWithInt:someValue]]==NSNotFound) 
      [values addObject:[NSNumber numberWithInt:someValue]]; 

     // now associate someValue with someKey in myDictionary 
     [myDictionary setObject:[NSNumber numberWithInt:someValue] forKey:someKey]; 
    } 

    // read the data in myDictionary enumerating the NSArray values 
    for (NSNumber * aValue in values){ 
     NSArray * objectsForValue = [myDictionary allKeysForObject:aValue]; 
     // now the data from objectsForValue are being used ... 
    } 

objectsForValue是空的,這不會發生所有的時間,但有規律的問題出現。如果我沒有弄錯,這在邏輯上是不可能的,除非[NSNumber numberWithInt:someValue]被作爲對象添加到myDictionary時被解釋爲NSNull,而同一個表達式在被添加到NSArray values時被當作對象處理。

和日誌記錄myDictionary我注意到這確實是發生了什麼事情。有人可以向我解釋爲什麼?

+2

爲什麼要製作數組和字典?爲什麼不只是設置鍵的對象,然後枚舉字典? –

+6

顯示記錄的字典。這裏沒有任何東西會神奇地引入'NSNull'對象,它們與'nil'不一樣。顯示CustomObjectAdoptingNSCopy如何實現複製*和*相等的代碼。 –

+1

有許多更合理的解釋比「NSNumber變得神奇地變成NSNull」更爲合理。例如,你的字典可能會在你的背後被修改,你可能在原始代碼中有一個錯誤,這個錯誤不存在於這個明顯假的例子中,等等。如果沒有實際的代碼,很難說明確的,但如果我是你,我會在跳到像神奇的NSNulls這樣的結論之前進行更徹底的調查。 – Chuck

回答

1

如果您尚未覆蓋-isEqual:-hash,則CustomObjectAdoptingNSCopy的副本不會相互等同。 NSObject的等式的默認實現是對象標識。由於NSDictionary複製密鑰,但副本不等於原始密鑰,因此除非您詢問密鑰並使用密鑰,否則無法從字典中檢索任何內容。原件不起作用。

+0

謝謝,這確實有很大的幫助! – magnus1969

相關問題