2011-05-09 132 views
1

allocWithZone返回的對象是否需要釋放?即是否與alloc和new相同?allocWithZone對象需要釋放

- (id) copyWithZone: (NSZone *) zone 
{ 
Engine *engineCopy; 
engineCopy = [[[self class] allocWithZone:zone]init]; 

return (engineCopy); 
} 

回答

1

是的,你仍然需要釋放它。查看文檔NSObject的: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/Reference/Reference.html

如果您正在使用管理存儲器(未 垃圾收集),這種方法 保留返回 之前的對象。返回的對象的保留 計數爲1,不是自動發佈的。 此方法的調用者是 負責釋放返回的 對象,使用release或 autorelease。

+0

但在教科書中,我在閱讀他們說以下方法在內存方面很好 - 請參閱編輯 – TheLearner 2011-05-09 14:21:29

+0

請參閱NSCopying的文檔,http://developer.apple.com/library/mac/#documentation/Cocoa/ Reference/Foundation/Protocols/NSCopying_Protocol/Reference/Reference.html#// apple_ref/occ/intf/NSCopying,但基本上調用copyWithZone假定與alloc類似,即它返回保留計數爲1的對象。 – 2011-05-09 14:37:27

+0

k so教科書是擰的 – TheLearner 2011-05-09 15:43:01

1

new結合了allocinit。這是需要釋放的alloc;幾乎不應該直接調用allocWithZone:alloc在內部調用它),並且主要是出於傳統原因。 更新同樣,copyWithZone:應該(幾乎)不會直接調用;但是,copy會隱式調用它。 copyWithZone:裏面可能是我唯一稱作allocWithZone:的地方。