Why is my NSNotification its observer called multiple times? Why is my NSNotification its observer called multiple times? ios ios

Why is my NSNotification its observer called multiple times?


Based on this description, a likely cause is that your viewcontrollers are over-retained and not released when you think they are. This is quite common even with ARC if things are over-retained. So, you think that you have only one instance of a given viewcontroller active, whereas you actually have several live instances, and they all listen to the notifications.

If I was in this situation, I would put a breakpoint in the viewcontroller’s dealloc method and make sure it is deallocated correctly, if that’s the intended design of your app.


In which methods did you register the observers?

Apple recommends that observers should be registered in viewWillAppear: and unregistered in viewWillDissapear:

Are you sure that you don't register the observer twice?


Ran into this issue in an application running swift. The application got the notification once when first launched. the notification increases the number of times you go into the background and come back. i.e

  • app launches one - add observer gets gets called once in view will appear or view did load - notification is called once
  • app goes into background and comes back, add observer gets called again in view will appear or view did load. notification gets called twice.
  • the number increases the number of times you go into background and come back.
  • code in view will disappear will make no difference as the view is still in the window stack and has not been removed from it.

solution:observe application will resign active in your view controller:

  NSNotificationCenter.defaultCenter().addObserver(self, selector: "applicationWillResign:", name: UIApplicationWillResignActiveNotification, object: nil)  func applicationWillResign(notification : NSNotification) {    NSNotificationCenter.defaultCenter().removeObserver(self)  }

this will make sure that your view controller will remove the observer for the notification when the view goes into background.


matomo