Why is my NSNotification its observer called multiple times?

后端 未结 5 2110
一个人的身影
一个人的身影 2020-12-15 04:48

Within an App I make use of several viewcontrollers. On one viewcontroller an observer is initialized as follows:

[[NSNotificationCenter defaultCenter] remov         


        
5条回答
  •  感情败类
    2020-12-15 04:59

    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.

提交回复
热议问题