Question or problem in the Swift programming language:
Is there a way to see if an object is already an observer for a type of notification?
Currently, each addObserver call is paired with removeObserver to avoid duplicate observers, but is there a way to see if an object is already an observer before invoking addObserver?
NSNotificationCenter.defaultCenter().removeObserver(self, name: CustomEvent, object: foo) NSNotificationCenter.defaultCenter().addObserver(self, selector: #("test"), name: CustomEvent, object: foo)
How to solve the problem:
Unfortunately no, there is not. Just like KVO, notification center doesn’t provide an API that lets us check whether an object (
self in this case) has already been registered as an observer or not.
You will have to yourself keep track using an bool variable and set it to “true” when you make an addObserver call and reset it when you call removeObserver.
Call addObserver again only when the bool is set to “false”.
There is no other way to figure out if object is already an observer.