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?
The second option is the correct one. You could also just do the following:
FileItem *item = [[[FileItem alloc] init] autorelease];
[[NSNotificationCenter defaultCenter] postNotificationName:@"dataReceived" object:self userInfo:item];
The conventional wisdom is that for every alloc
, copy
, or retain
, you need a corresponding release
(or autorelease
). Doing anything more is almost guaranteed to result in your object being overreleased.