2010-06-10 68 views
1

我想用objectA創建一個NSMutableDictionary(dictA)。當我嘗試查看我的字典(NSLog)時,每個鍵都指向相同的地址。我有一個objectA_1,它是objectA類型並用於設置字典。另外,如果我嘗試getObject,我總是得到添加到字典中的最後一個鍵/值。我嘗試了setValue並得到了相同的結果。我的對象A有什麼問題嗎?發佈方法無法正常工作?當我不應該時,我會保留嗎?謝謝。NSMutableDictionary內存/地址,發佈不起作用?

dictA = [[NSMutableDictionary alloc] init]; 
objectA *objectA = [[objectA alloc] init]; 

objectA.ID = 5; 
[dictA setObject:objectA forKey:@"apple"]; 
[objectA release]; 

objectA.ID = 50; 
[dictA setObject:objectA forKey:@"japan"]; 
[objectA release]; 

objectA.ID = 6; 
[dictA setObject:objectA forKey:@"paris"]; 
[objectA release]; 

objectA.ID = 11; 
[dictA setObject:objectA forKey:@"pizza"]; 
[objectA release]; 

// NSLog的:

apple = "objectA: 0x175830"; 
japan = "objectA: 0x175830"; 
paris = "objectA: 0x175830"; 
pizza = "objectA: 0x175830"; 
+0

您是否爲objectA實現了'description'方法? – Senseful 2010-06-10 03:37:56

回答

1

我假設你的意思是:

objectA *objectA_1 = [[objectA alloc] init]; 

你應該只釋放對象只有一次。這是因爲每次字典刪除元素時,它都會自動調用對象的釋放,因爲每次將其添加到字典時,它都會自動保留該對象。

試試這個代碼,而不是:

dictA = [[NSMutableDictionary alloc] init]; 
objectA *objectA_1 = [[objectA alloc] init]; 

[dictA setObject:objectA_1 forKey:@"apple"]; 
[dictA setObject:objectA_1 forKey:@"japan"]; 
[dictA setObject:objectA_1 forKey:@"paris"]; 
[dictA setObject:objectA_1 forKey:@"pizza"]; 
[objectA_1 release]; 

此外,還需要實現您的自定義對象的description方法,這樣的NSLog知道如何進行打印。