profile for monkeydom at Stack Overflow, Q&A for professional and enthusiast programmers

cocoa-dom

coding bits I use, come across, like, hate, the whole shebang.

twitter | github | mastodon     rant-dom     rss | archive

Permalink
Home

Be very careful when calling -[NSNotificationCenter removeObserver:]

rentzsch:

Samuel Défago :

Never ever use -[NSNotificationCenter removeObserver:] to unregister from notification events, except from a dealloc method. This might cancel registrations made by a parent class, and you cannot know how a parent class is implemented (at least you shouldn’t care). Stick to this rule even if your parent class is NSObject: Your class hierarchy might change in the future, and you do not want to run into problems when you don’t have to, do you?

(via Cédric Luthi )

I strongly disagree. There are multiple situation e.g. on the iPhone where registering and deregistering in the [will|did]Appear/Disappear: methods is valid, helpful and good style. (And I took the liberty to fix the classname)

Update: Permature posting is premature. (note to self: always read the whole referenced article).

So to add some actual wisdom to this subject: Calling the -[NSNotificationCenter removeObserver:] should be confined to situations where you get rid of the object. So I agree dealloc can be the place, but it also can be somewhere up in the chain if you invalidate your object where you already have the knowledge it should go away, but it is not dealloced memory wise. In complex cocoa apps you run in these situations. Also helpful in these cases: [NSObject cancelPreviousPerformRequestsWithTarget: self];