Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is calling [self release] allowed to control object lifetime?

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];
} 
like image 602
Philippe Leybaert Avatar asked Sep 06 '09 11:09

Philippe Leybaert


1 Answers

If you see this in code, its probably wrong. However there are legitimate response for it in certain circumstances that are arguably defensible. (So make sure you are doing it for the right reasons.)

A good example of when this makes sense, 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. In this situation the code/function that created the 'url downloader' may no longer even be in memory, i.e. if it was called in response to a user selection a menu item or an action in a view controller that is no longer on the screen.

This is useful when the code that creates the "download" object doesn't care if the download completes or not.

like image 120
Jay Avatar answered Oct 12 '22 23:10

Jay