iphone - 在将对象作为用户数据发送到通知中心之前,我是否需要自动释放该对象?

标签 iphone cocoa memory-management nsnotifications

我需要使用 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];

传统观点是,对于每个alloccopyretain,您都需要一个相应的release (或自动释放)。做更多的事情几乎肯定会导致您的对象被过度释放。

关于iphone - 在将对象作为用户数据发送到通知中心之前,我是否需要自动释放该对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/948401/

相关文章:

iphone - srandom(time(NULL)) 给出警告 - 指向没有转换的整数的指针

iphone - 从 CLLocationManager 授权警报中检测按钮按下

objective-c - 自定义 NSView 的 subview 正在调整自身大小以适应其 super View

objective-c - 如何将字符串部分与 Objective-C 中的 NSArray 值进行匹配

c++ - 在 world.iprobe 上 boost MPI 崩溃

objective-c - 另一个 "Retain, then Release"问题

iphone - 在字符串文件中存储键/值对

iphone - NSDate 和 NSDateFormatter 问题

objective-c - 为什么我可以在 NSWindowController 中实现 NSDraggingDestination 方法?

python - 当我分配一个巨大的 ndarray 时,numpy 空在做什么?