swiftnsnotificationcenternsnotificationsnsnotification

Observer never called


I have two functions

override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        NSNotificationCenter.defaultCenter().addObserverForName("personalDataDidLoad", object: self, queue: NSOperationQueue.mainQueue()) {_ in
            print("Received notification")
            self.showPersonalData()
        }

        loadPersonalData()
    }



func loadPersonalData() {
    //load data
    print("personal data loaded")
    NSNotificationCenter.defaultCenter().postNotificationName("personalDataDidLoad", object: nil)

but for some reason this outputs

 personal data loaded

instead of the expected

 personal data loaded
 Received notification

I'm probably missing something obvious, but I don't see it right now....

I also tried addObserver with selector: "showPersonalData:" but this throws an unrecognized selector exception..


Solution

  • The problem is with the 2nd parameter in postNotificationName and addObserverForName: object. When you add an observer, and pass a non-nil object value, this means that the observer block will run when a notification comes from that object, and from that object only. However, when you fire the notification, you do object: nil. So your notification is ignored.

    On the other hand, passing a nil value for object means, "I want to receive this notification regardless of who sends it".

    So you need to make sure the object value is the same in both places: either self or nil.