我需要使用 postNotificationName:object:userInfo:
方法发布通知,并且我将自定义类 FileItem
作为 userInfo
传递> 这样我就可以在另一端获取它。我应该像这样使用 autorelease
FileItem *item = [[[FileItem alloc] init] autorelease];
[[NSNotificationCenter defaultCenter] postNotificationName:@"dataReceived" object:self userInfo:item];
[item release];
或者我可以在将对象传递到默认通知中心后立即分配
然后立即释放
对象吗?
FileItem *item = [[FileItem alloc] init];
[[NSNotificationCenter defaultCenter] postNotificationName:@"dataReceived" object:self userInfo:item];
[item release];
我试图在这里达成约定,因为我假设每当我将一个对象作为消息中的参数传递给另一个对象时,接收对象将在需要时执行保留,并且我可以安全地释放所述参数?
最佳答案
第二个选项是正确的。您也可以执行以下操作:
FileItem *item = [[[FileItem alloc] init] autorelease];
[[NSNotificationCenter defaultCenter] postNotificationName:@"dataReceived" object:self userInfo:item];
传统观点是,对于每个alloc
、copy
或retain
,您都需要一个相应的release
(或自动释放
)。做更多的事情几乎肯定会导致您的对象被过度释放。
关于iphone - 在将对象作为用户数据发送到通知中心之前,我是否需要自动释放该对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/948401/