iosswiftnsnotificationcenternsnotificationsnsnotification

when to call removeObserver for nsnotificationcenter


I have a view controller with a button action:

@IBAction func MultiplayerButtonClick(sender: AnyObject) {
            NSNotificationCenter.defaultCenter().addObserver(
              self, 
              selector: NotificationConstants.pvpConnEstablishedSelector, 
              name: NotificationConstants.pvpConnEstablishedString , 
              object: nil)

            setUpGameScene()
            initiateMultiplayerGC()
    }

and somewhere, a notification is posted that triggers the selector for this observer:

//action for pvpConnEstablishedSelector
func hideMainView() {
   MenuView.hidden = true
   //NSNotificationCenter.defaultCenter().removeObserver(self) ???
}

is it a good place to call removeObserver in the function that is the selector for the observer?

or is there a more suitable place to do this?


Solution

  • A couple of observations:

    1. I infer from your code comment that you are contemplating removing the observer inside the selector for that particular notification. That is a fine practice.

      I'd be wary about just calling removeObserver, though, because that will remove all observers that you may have set up. If you are calling this inside the routine that is the selector for a particular notification, then I might be inclined to remove only that particular notification:

      NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationConstants.pvpConnEstablishedString, object: nil)
      

      Yes, at this point, you may only be observing a single notification, so this may feel unnecessary, but if at some future date you add completely separate notification handling code for a different notification, you want to make sure that you don't accidentally remove all observers when handling a particular notification.

    2. You might want to be sensitive to the possibility that this view controller may be dismissed before the notification comes in. In that case, it might be prudent to also add removeObserver in the deinit method for the view controller.

      In this case, the simple removeObserver(self) is prudent (because it's reasonable to remove all observers when the view controller is deallocated).