I have an object
id currentObject;
which I want to pass through notification. The problem is I don’t know how to release it correctly and the memory management documentation is driving me crazy.
I am doing it like this right now:
[[NSNotificationCenter defaultCenter] postNotificationName:@"MessageReceived" object:nil userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[currentObject copy], @"key", nil]];
[currentObject release];
Should it rather be:
[[NSNotificationCenter defaultCenter] postNotificationName:@"MessageReceived" object:nil userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[currentObject autorelease], @"key", nil]];
?
(it is for the iPhone, iOS4.0)
Thanks in advance!
Either way is OK. Although there is a marginal difference between those two approaches, it shouldn’t make any practical difference in this case. As long as you’re releasing your own ownership in one way or the other, you’ll be fine. The dictionary and notification centre will deal with their own ownership issues in their own time.
EDIT: Oops, missed something. What I said at first still applies in general, BUT in the first example you are calling
copyoncurrentObject. This creates a new bit of ownership — which you immediately forget, and therefore produce a memory leak.Since we don’t see where you create
currentObject, it’s possible both versions over-release that too. But assuming youallocit, you’re sufficiently releasing that. But if you insist on callingcopy— probably unnecessary, though you’d know more about whatcurrentObjectis and what might later happen to it — you need toreleasethe new copy too, eg by wrapping thecopycall inautorelease, like so:If this is unclear, have another good read of the object ownership docs.