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)
First, register an observer for a notification with: addObserver(_:selector:name:object:) Then, post a notification with post(name:object:userInfo:) … … after which your selector is called. And don't forget to remove the observer with removeObserver()
Observer is a behavioral design pattern that allows some objects to notify other objects about changes in their state. The Observer pattern provides a way to subscribe and unsubscribe to and from these events for any object that implements a subscriber interface.
A notification dispatch mechanism that enables the broadcast of information to registered observers.
Removing registered observer For Selector approach, use NotificationCenter. default. removeObserver(self, name: notificationName , object: nil) , to remove the observer. For Block based approach, save the token you obtained by registering for notification in a property.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With