swiftobserversnotificationcenter

NotificationCenter is observing multiple times


I'm having a problem in my implementation using observers in Swift, The problem is I'm having the same observer multiple times so I make one function more than once.

How can I validate if I'm observing the same observer already before observing it again?

NotificationCenter.default.addObserver(self, selector: #selector(myFunction(notification:)), name: NSNotification.Name(rawValue: "SameObserver"), object: nil)

Thanks for your help


Solution

  • By making sure to balance your calls to addObserver and removeObserver. Alternately, you could create a boolean somewhere that indicates that you've already called addObserver, but it's better just to balance your calls.

    The best way to balance your calls is to tie them to the observer's lifetime or lifecycle. For lifetime you would call addObserver in init and removeObserver in deinit (or use one of the forms that automatically removes your observation). For lifecycle (for example in a ViewController), you would call addObserver in viewWillAppear and removeObserver in viewDidDisappear.

    There is no mechanism for querying NotificationCenter.