Note that there are some explanatory texts on larger screens.

plurals
  1. POWarning for iOS/iPhone users about duplicate NSNotification observations
    text
    copied!<p>This isn't a question so much as a warning to others to save them some time.</p> <p>NSNotificationCenter on iOS 3/iPhone OS 3 (I'm assuming also Mac OS X and iOS 4) has the following behavior:</p> <p>If you register yourself multiple times for the exact specific notification, NSNotificationCenter will <strong>NOT</strong> recognize the redundancy and instead will fire off as many notifications to you as you've registered an observation for.</p> <p>This is almost never the behavior you want to see and is almost always accidental.</p> <p>Example:</p> <p>I want my view controller to receive notifications from a singleton network object when new data comes in:</p> <pre><code>- (void) viewDidLoad { [super viewDidLoad]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(newDataArrived:) name:NewDataArrivedNotification object:[NetworkListener sharedNetworkListener]]; } </code></pre> <p>but earlier I'd already put the same thing in <code>viewWillAppear</code>:</p> <pre><code>- (void) viewWillAppear { [super viewWillAppear]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(newDataArrived:) name:NewDataArrivedNotification object:[NetworkListener sharedNetworkListener]]; } </code></pre> <p>Note that it's <strong>exactly</strong> the same notification, resolving to the same observer, sender and notification name.</p> <p>In this case, if I don't remove one of those addObserver calls, I'll get duplicate notifications to my view controller.</p> <p>In a multi-threaded environment, this is a world of hurt. Trust me.</p> <p>Just putting this out there in case there are others who run into something like this.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload