-2

I recently looked into some swift code and I found this: adding the observer and then removing it right after. What's the logic behind that?

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "displayPushMessage:", name: "displayMessage", object: nil)

}

//adding the observer and removing it right after whhy?? where is the logic

override func viewDidDisappear(animated: Bool) {
    super.viewDidDisappear(animated)
    NSNotificationCenter.defaultCenter().removeObserver(self, name: "displayMessage", object: nil)
}

func displayPushMessage (notification:NSNotification) {
Jonathan Meguira
  • 1,860
  • 2
  • 12
  • 15

1 Answers1

1

Because it's not "right after" in terms of program execution time. Some observers make sense to listen for the lifetime of the object (view controller in this case). Others are only applicable when the VC is visible -- for example, you have no need to listen for messages whose purpose is to update UI elements (and take execution time, memory, etc) when it's not possible to see them.

Brad Brighton
  • 2,179
  • 1
  • 13
  • 15