简体   繁体   中英

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..

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 .

Is there a reason you need to use addObserverForName(_:object:queue:usingBlock:) ?

Try this instead:

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)
    NSNotificationCenter.defaultCenter().addObserver(self, "personalDataDidLoadNotification:", name: "personalDataDidLoad" object: nil)
    loadPersonalData()
}

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

func personalDataDidLoadNotification(notification: NSNotification) {
    print("notification recieved")
}

Another answer to the title question (but not this example) but will hopefully help others in the situation I have been in for the last 3 hours:

Make sure your notificationcenter observer is added inside a class that has a persisted instance. I created the observer inside a class that was called as eg MyClass().setupNotification inside a local method of another class.

This meant the observer was immediately deleted and didnt persist against any instance.

Schoolboy error - but hope this helps others searching for this.

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