在将对象作为用户数据发送到通知中心之前,我是否需要自动释放该对象?
我需要使用 postNotificationName:object:userInfo:
方法发布通知,并且我将自定义类 FileItem
作为 userInfo
传递,所以我可以在另一端获取它。 我应该像这样使用autorelease
FileItem *item = [[[FileItem alloc] init] autorelease];
[[NSNotificationCenter defaultCenter] postNotificationName:@"dataReceived" object:self userInfo:item];
[item release];
,还是可以直接alloc
,然后在将对象传递到默认通知中心后立即release
对象?
FileItem *item = [[FileItem alloc] init];
[[NSNotificationCenter defaultCenter] postNotificationName:@"dataReceived" object:self userInfo:item];
[item release];
我试图在这里达成约定,因为我假设每当我将一个对象作为消息中的参数传递给另一个对象时,接收对象将在需要时执行保留,并且我可以安全地释放所述参数?
I need to post a notification using postNotificationName:object:userInfo:
method, and I'm passing a custom class FileItem
in as userInfo
so I can obtain it on the other end. Should I use autorelease
like this
FileItem *item = [[[FileItem alloc] init] autorelease];
[[NSNotificationCenter defaultCenter] postNotificationName:@"dataReceived" object:self userInfo:item];
[item release];
or can I just alloc
and then release
the object immediately after passing it to the default notification center?
FileItem *item = [[FileItem alloc] init];
[[NSNotificationCenter defaultCenter] postNotificationName:@"dataReceived" object:self userInfo:item];
[item release];
I'm trying to get convention here as I assume that whenever I pass an object as parameter in a message to another object, the receiving object would do a retain if it needs to, and that I can safely release the said parameter?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
autorelease
只是意味着“稍后发送release
”。 向同一个对象发送autorelease
然后发送release
会释放该对象两次。 正如马特·鲍尔所说,你的后一个例子和他的例子是等价的。更重要的是,你只释放你拥有的东西。 一旦你释放了它,你就不再拥有它,并且应该认为它不再属于你了。 在您的第一个示例中,在第一次发布后,您已不再拥有该对象。 第二次释放显然是错误的,因为它释放了一个不属于您的对象。
并且永远释放其他对象拥有的对象,除非您也拥有它。
autorelease
just means “sendrelease
to this later”. Sendingautorelease
and thenrelease
to the same object is releasing it twice. As Matt Ball says, your latter example and his example are equivalent.More to the point, you only release what you own. Once you release it, you stop owning it, and should consider it no longer yours. In your first example, after the first release, you've stopped owning that object. The second release is then clearly wrong, because it releases an object you don't own.
And never release an object that some other object owns, unless you also own it.
第二个选项是正确的。 您也可以执行以下操作:
传统观点是,对于每个
alloc
、copy
或retain
,您都需要一个相应的发布
(或自动释放
)。 做更多的事情几乎肯定会导致您的对象被过度释放。The second option is the correct one. You could also just do the following:
The conventional wisdom is that for every
alloc
,copy
, orretain
, you need a correspondingrelease
(orautorelease
). Doing anything more is almost guaranteed to result in your object being overreleased.