George Asda
George Asda

Reputation: 2129

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?

Upvotes: 0

Views: 844

Answers (1)

ArtSabintsev
ArtSabintsev

Reputation: 5180

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?

Upvotes: 3

Related Questions