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
By making sure to balance your calls to
addObserverandremoveObserver. Alternately, you could create a boolean somewhere that indicates that you've already calledaddObserver, 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
addObserverininitandremoveObserverindeinit(or use one of the forms that automatically removes your observation). For lifecycle (for example in a ViewController), you would calladdObserverinviewWillAppearandremoveObserverinviewDidDisappear.There is no mechanism for querying NotificationCenter.