0

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.

Itay Brenner
  • 800
  • 6
  • 19
Mvdm
  • 3
  • 2
  • Did you add the observer before posting the notification? I mean, receiveNotification() should be called before you post the notification from the ViewController 1. Also, you cannot release the ViewController 2 because the observer will be released – Itay Brenner Sep 24 '20 at 01:09
  • I added the observer after posting the notification. How do I receive a notification if the notification hasn't been posted yet?. What do you mean by "Also, you cannot release the ViewController 2 because the observer will be released". Sorry I am quite new to this – Mvdm Sep 24 '20 at 01:12
  • If you want to communicate events from one VC to another, you will need a Queue, in this case you can just create a Singleton with a list which you can call to see if there is a new "Date" event. For releasing VC 2 you should take a look at how memory works on iOS and ARC – Itay Brenner Sep 24 '20 at 01:16
  • Oh I just got it, thank you so much, I was stuck on this for hours. So an observer needs to be added first as it "Looks" for the post with the same NSNotification.Name. – Mvdm Sep 24 '20 at 01:20
  • Exactly, NSNotificacionCenter is a variation of the Observer Pattern, you can read about it here: https://www.tutorialspoint.com/design_pattern/observer_pattern.htm ( I will add this as answer for future users) – Itay Brenner Sep 24 '20 at 01:21

1 Answers1

0

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.

Itay Brenner
  • 800
  • 6
  • 19