Ios Swift-notification-observer被多次调用

Ios Swift-notification-observer被多次调用,ios,swift,nsnotificationcenter,Ios,Swift,Nsnotificationcenter,我有viewController和内置的viewDidLoad NSNotificationCenter.defaultCenter().addObserver(self, selector: "showNextQuestions", name: "showNextQuestionsID", object: nil) 在另一个控制器中,我有 NSNotificationCenter.defaultCenter().postNotificationName("showNextQuestionsI

我有viewController和内置的viewDidLoad

NSNotificationCenter.defaultCenter().addObserver(self, selector: "showNextQuestions", name: "showNextQuestionsID", object: nil)
在另一个控制器中,我有

NSNotificationCenter.defaultCenter().postNotificationName("showNextQuestionsID", object: nil)
如果我从应用程序返回并再次启动,函数showNextQuestionID将触发两次

我试着用

func applicationDidEnterBackground(application: UIApplication) {
    NSNotificationCenter.defaultCenter().removeObserver(self, name: "showNextQuestionsID", object: nil)
}
但这没用

和在viewController中

deinit {
    NSNotificationCenter.defaultCenter().removeObserver(self)
}

如何解决此问题?

您没有在正确的位置删除通知观察员。在视图控制器子类中注册观察者,需要在同一个类中删除它。一个合乎逻辑的地方是重写viewwilldemouse方法。在视图控制器子类中放置以下代码:

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)

    NSNotificationCenter.defaultCenter().removeObserver(self)
}
也删除

 NSNotificationCenter.defaultCenter().removeObserver(self, name: "showNextQuestionsID", object: nil)
来自您的AppDelegate。在AppDelegate中提供“self”参数时,它引用的是AppDelegate类,而不是视图控制器。在视图控制器子类中调用以删除通知观察者时,self是您的视图控制器,这正是您所需要的


最后,当您在没有其他参数的情况下调用simply removeObserver(self)时,它将注销该对象的所有观察者。这样,您就不必逐一查看并按名称列出每个观察者。

将观察者放入AppDelegate或singleton中,以便您可以在应用程序状态期间轻松添加和删除观察者。

应用程序标识符背景
Denit
应该可以

问题在于您试图在
ApplicationIdentinterBackground
中删除观察者的方式。您正试图从AppDelegate中删除观察者,需要从ViewController中删除观察者

要解决此问题,请执行以下操作:

1) 在视图控制器中侦听UIApplicationIdentinterBackground通知:

func init() {
  super.init()

  NSNotificationCenter.defaultCenter().addObserver(self, selector: "myAppDidEnterBackground", name: UIApplicationDidEnterBackgroundNotification, object: nil) 
}
2) 实现侦听
UIApplicationIdentinterBackgroundNotification的方法

func myAppDidEnterBackground() {
NSNotificationCenter.defaultCenter().removeObserver(self, name: "showNextQuestionsID", object: nil)
}

3) 额外的。您还可以监听
UIApplicationWillEnterForegroundNotification
,以便再次添加您的自定义通知

是否有其他不显示的方式将消失?我需要更改ViewController中的UI,当用户在另一个控制器上时,在其中注册了观察者。必须在用户到达此处之前更改控制器