Do I need to auto-update an object before sending it to NotificationCenter as user data?

I need to send a notification using the postNotificationName:object:userInfo: , and I pass the user-defined FileItem class as userInfo to get 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 object right after passing it to the default notification center?

 FileItem *item = [[FileItem alloc] init]; [[NSNotificationCenter defaultCenter] postNotificationName:@"dataReceived" object:self userInfo:item]; [item release]; 

I am trying to conclude an agreement here, because I assume that whenever I pass an object as a parameter in a message to another object, the receiving object will save if necessary, and that I can safely release the specified parameter

+4
source share
2 answers

The second option is correct. You can also do the following:

 FileItem *item = [[[FileItem alloc] init] autorelease]; [[NSNotificationCenter defaultCenter] postNotificationName:@"dataReceived" object:self userInfo:item]; 

The traditional wisdom is that for each alloc , copy or retain you need the appropriate release (or autorelease ). Doing anything more is almost guaranteed to result in your object being deleted.

+3
source

autorelease simply means "send release to this later." By sending autorelease and then release to the same object, it releases it twice. As Matt Ball says, your last example and its example are equivalent.

Moreover, you only release what you have. After you release it, you will cease to own it, and you should no longer count it. In the first example, after the first release, you ceased to own this object. The second version is then clearly wrong, because it frees an object that you do not have.

And never release an object that owns any other object unless you also own it.

+2
source

Source: https://habr.com/ru/post/1285718/


All Articles