copyWithZone 返回值所有权并保留计数
我在苹果文档中读到有关 copyWithZone 的内容:
“返回的对象隐式由发送者保留,发送者负责释放它”。
因此,如果我写这个 :
- (id)copyWithZone:(NSZone *)zone {
MyObject* obj = [[[[self class] allocWithZone:zone] init] autorelease];
[obj fillTheObj];
return obj;
}
并调用 : ,
MyStuff* obj = [varobj copy];
obj
会被保留吗?如果我不设置自动释放,那么保留计数会怎样?
I read in the apple documentation about copyWithZone :
"The returned object is implicitly retained by the sender, who is responsible for releasing it".
So if I write this :
- (id)copyWithZone:(NSZone *)zone {
MyObject* obj = [[[[self class] allocWithZone:zone] init] autorelease];
[obj fillTheObj];
return obj;
}
and I call :
MyStuff* obj = [varobj copy];
will obj
be retained? What about the retain count if I don't set autorelease?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不要在您的
copyWithZone
方法中自动释放它,否则您将不会拥有它(并且可能甚至无法用它做任何事情)。删除自动释放,
obj
将适当保留在MyStuff
复制中。您只需在完成后release
它即可。Apple 的句子是说发送者(即您的
MyStuff *obj
初始化)拥有所有权并需要释放它。 “发送者”指的是发送copy
消息的对象,而不是您的copyWithZone
方法。Do not autorelease it in your
copyWithZone
method or you won't own it (and likely won't be able to even do anything with it).Remove the autorelease and
obj
will be appropriately retained in theMyStuff
copying. You simply need torelease
it when you're done with it.The Apple sentence is saying that the sender -- which is your
MyStuff *obj
initialization -- has ownership and needs to release it. "Sender" refers to the object that sent thecopy
message, not yourcopyWithZone
method.