24

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.

Duck
  • 34,902
  • 47
  • 248
  • 470
  • Possible duplicate of [How to avoid adding multiple NSNotification observer?](http://stackoverflow.com/questions/5658426/how-to-avoid-adding-multiple-nsnotification-observer) – Greg Leszek Jan 04 '16 at 12:59

2 Answers2

35

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.
  • 33,468
  • 5
  • 78
  • 96
  • 4
    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? – Duck Sep 27 '10 at 01:31
  • 2
    @Digital Robot; I do this all the time. It doesn't crash. – Jamie Chapman Sep 27 '10 at 20:41
  • 7
    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. Sep 28 '10 at 19:52
  • 1
    Is there a race condition between the removal and the add observer where a notification could be fired and fail to trigger the observer? – David James May 11 '15 at 11:15
0

Remove observer before adding it:

How to avoid adding multiple NSNotification observer?

For unit testing you should mock NSNotificationCenter as it is dependency.

Umit Kaya
  • 5,771
  • 3
  • 38
  • 52
Greg Leszek
  • 3,530
  • 1
  • 17
  • 16