简体   繁体   中英

NSNotificationCenter observer doesn't work

I am trying to post a notification as follows:

  NSNotificationCenter .defaultCenter() .postNotificationName("name", object: nil)

from within a function of viewControllerA

then in ViewControllerB in viewDidLoad

   NSNotificationCenter.defaultCenter().addObserver(self, selector: "doSomething:", name:"name", object: nil)

But the doSomething: is never called!

any ideas?

Here's what the code should like in your two controllers.

In the subscribing/listening ViewController :

func viewDidLoad() {
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "doSomething:", name: "name", object: nil)
}

func doSomething(notification: NSNotification) {
    print("Notification was posted.")
}

In the publishing/posting ViewController :

func viewDidLoad() {
    NSNotificationCenter.defaultCenter().postNotificationName("name", object: nil)
}

If it's not working, it might be due to your app's architecture:

  • Are both ViewControllers currently loaded in memory?
  • Is the observer added before the notification is sent?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM