allocWithZone返回的對象是否需要釋放?即是否與alloc和new相同?allocWithZone對象需要釋放
- (id) copyWithZone: (NSZone *) zone
{
Engine *engineCopy;
engineCopy = [[[self class] allocWithZone:zone]init];
return (engineCopy);
}
allocWithZone返回的對象是否需要釋放?即是否與alloc和new相同?allocWithZone對象需要釋放
- (id) copyWithZone: (NSZone *) zone
{
Engine *engineCopy;
engineCopy = [[[self class] allocWithZone:zone]init];
return (engineCopy);
}
是的,你仍然需要釋放它。查看文檔NSObject的: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/Reference/Reference.html
如果您正在使用管理存儲器(未 垃圾收集),這種方法 保留返回 之前的對象。返回的對象的保留 計數爲1,不是自動發佈的。 此方法的調用者是 負責釋放返回的 對象,使用release或 autorelease。
new
結合了alloc
和init
。這是需要釋放的alloc
;幾乎不應該直接調用allocWithZone:
(alloc
在內部調用它),並且主要是出於傳統原因。 更新同樣,copyWithZone:
應該(幾乎)不會直接調用;但是,copy
會隱式調用它。 copyWithZone:
裏面可能是我唯一稱作allocWithZone:
的地方。
但在教科書中,我在閱讀他們說以下方法在內存方面很好 - 請參閱編輯 – TheLearner 2011-05-09 14:21:29
請參閱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
k so教科書是擰的 – TheLearner 2011-05-09 15:43:01