I want to create an object in Objective C but I don't hold a reference to it.
Is it allowed to let the object control its own lifetime by calling [self release]?
In case you're wondering why I need this: I want to create an object that subscribes to some notifications, but after a while the object is no longer needed and should go away.
So, is the following allowed?
- (void) destroyMyself {
[[NSNotificationCenter defaultCenter] removeObserver:self];
[self release];
}
Source: Tips4all
The rules are simple. You should only release an object if you own it. i.e. the object was obtained with a method starting "new" or "alloc" or a method containing copy.
ReplyDeleteCocoa Memory Management Rules
An object must not therefore do [self release] or [self autorelease] unless it has previously done [self retain].
I have done this many times before, it is perfectly fine to do, as long as you are doing it for the right reasons.
ReplyDeleteFor example, The best example of its usage is when you create an object that goes off to download a url. The object sits in memory while downloading the url, then sends a message to its delegate saying the data is ready (or url couldn't be downloaded). Once its message has been sent it destroys itself as its no longer needed.
This is useful when the code that creates the "download" object doesn't care if the download completes or not.
It's legal, but be careful. You want to be sure nothing else is going to send you a message after you release yourself.
ReplyDeleteI've done this kind of thing for a faulting scheme back before we had CoreData.
Well part of the protocol is that if you send release to self, then you should have sent retain once as well, which I suppose you do. Then there is nothing fishy. I mean the allocing code must be able to control the lifetime of your instance; it itself can only prolong its life, never make it shorter (since making it shorter, then you'd suddenly leave the allocing owner of the instance with an invalid pointer).
ReplyDeleteTo quote the great philosopher Alicia Silverstone, "I had an overwhelming sense of ickiness" when I read that. But I couldn't really tell you why.
ReplyDeleteI think I would use autorelease rather than a simple release since you're still executing code in self when you call it, but other than that I can't think of any technical reasons why it wouldn't work.