NSNotificationCenter: Add an observer, but only if it is not registered for observation? Can I request an observation status for an object?

Is there a way to find out if an object is already an observer for a notification type?

Currently, every addObserver call addObserver paired with removeObserver to avoid duplicate observers, but is there a way to see if the object is already an observer before addObserver ?

 NSNotificationCenter.defaultCenter().removeObserver(self, name: CustomEvent, object: foo) NSNotificationCenter.defaultCenter().addObserver(self, selector: #("test"), name: CustomEvent, object: foo) 
+5
source share
2 answers

Unfortunately no, no. Like KVO, the notification center does not provide an API that allows us to check whether an object ( self in this case) was already registered as an observer or not.

+7
source

You will have to independently monitor the use of the bool variable and set it to true when addObserver is called and reset when removeObserver is called. Call addObserver again only if bool is set to false.

There is no other way to find out if an object is already an observer.

+3
source

Source: https://habr.com/ru/post/1247802/


All Articles