Reputation: 585
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
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
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
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