2011-02-26 21 views
2

從代碼:數組c在Objective-C保持指針對象已經解除分配

Thing *thingA = [[Thing alloc]init]; 
// thingA pointer reference 0x00998 

Thing *things[] = {thingA}; 

[thingA release]; 
// release method of the Thing class correctly invoked 

thingA = nil; 
// thingA pointer reference now is 0x0 

NSLog(@"%d", things[0]); 
// odd, because things[0] still maintains the pointer reference 0x00998 

爲什麼元件things[0]保持指針參考0x00998? 在這種thingAdealloc通過release後設置爲nil時刻(引用thingA現在0x0)如何things[0]仍然參考0x0998? 我認爲things[0]指針會看起來與0x0

回答

5

thingA = nil;僅影響thingA參考。它不會影響任何其他引用或對象本身。

可以使這個例子簡單一點

Thing *thingA = [[Thing alloc]init]; 
Thing *thingB = thingA; 

[thingA release]; 
thingA = nil; 

// thingA is nil, but thingB still has old reference 

注意,既然對象本身被釋放,你不應該使用thingB參考:內存它指向可用於別的東西了。

+0

事* thingB = [thingA保留];會讓你繼續使用B後釋放一個? – Mark 2011-02-26 03:30:41

+0

@Mark在某種程度上。 'retain'調用會將'retain count'增加到2,'release'調用會將它減少回1.但是你不能單獨釋放A和B:它們是指向同一個對象的引用。也就是說,有兩個引用,但只有一個對象。在你的例子中,它不會被釋放。您可以查看[文檔](http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html)瞭解詳情。 – 2011-02-26 03:35:46

+0

thingB可以存在,甚至錯誤,我沒有設置thingB到零? – Tortuo 2011-02-26 03:44:22