swiftxcodensnotificationcenteraddobserver

Selector function not being entered when observer is added


In my first view controller, I post the notification with the following code:

NotificationCenter.default.post(name: Notification.Name("date"), object: formattedDate)

I then "receive" the notification in a second view controller with the following code:

func receiveNotification () {
    NotificationCenter.default.addObserver(self, selector: #selector(self.didGetTheDate(_:)), name: NSNotification.Name("date"), object: nil)
}

@objc 
func didGetTheDate(_ notification: Notification) {
    print("In did get date")
    date = notification.object as! String    
}

However, the function "didGetTheDate" never gets called. I have triple checked that the function "receiveNotification" gets called as I have added print statements to check this.

Can somebody please help me with this.


Solution

  • NSNotificacionCenter is a variation of the Observer Pattern, you can read about it here

    This means that you will have to register an Observer before posting any notification. If you post anything before that, the NSNotificationCenter will look at the observer for name and will see that nobody is listening for it, thus nothing will happen.