Fr4nc3sc0NL
Fr4nc3sc0NL

Reputation: 585

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

Upvotes: 2

Views: 1070

Answers (3)

Charlie S
Charlie S

Reputation: 4604

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

Upvotes: 0

TotoroTotoro
TotoroTotoro

Reputation: 17622

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.

Upvotes: 3

Kyle Redfearn
Kyle Redfearn

Reputation: 2281

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")
}

Upvotes: 0

Related Questions