tags:

views:

29

answers:

1

At some point in a code one may add something like

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doSomething) name:@"Hello" object:nil];   

How do I test if this notification is already active on the queue or has been removed, to prevent adding a duplicate?

thanks.

+2  A: 

If you mean "testing for whether you've already registered as an observer for the notification", I don't think there's an easy way apart from posting the notification and seeing you get a callback (with possibly disastrous effects).

If there's a danger of a double-add, I usually use [[NSNotificationCenter defaultCenter] removeObserver:self name:foo object:bar] before the add.

Registering for notifications does not happen on a queue.

tc.
Isn't danger to remove an observer without knowing if there's an observer to remove? Isn't like releasing an already released object? wouldn't that crash the app?
Digital Robot
@Digital Robot; I do this all the time. It doesn't crash.
Jamie Chapman
thanks!!!!!!!!!
Digital Robot
1. It's not like a double-release/double-free, since NSNotificationCenter does not retain the "target" or "object" (presumably it retains "name"). 2. NSNotificationCenter keeps track of (target,selector,name,object) tuples. It *must* do, because it has to know what to remove when you call removeObserver: or removeObserver:name:object:. 3. "remove" methods generally imply "don't do anything if it hasn't been added (e.g. `-[NSMutableSet removeObjectForKey:]`, `-[NSArray removeObject:]`)
tc.