Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSNotificationCenter: Add observer but only if not registered to observe? Possible to query observing status for an object?

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) 
like image 377
Crashalot Avatar asked Apr 24 '16 08:04

Crashalot


People also ask

How do I add an observer in Swift 5?

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()

How do I use observers in Swift?

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.

What is Nsnotificationcenter in Swift?

A notification dispatch mechanism that enables the broadcast of information to registered observers.

How do I remove a specific observer in Swift?

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.


2 Answers

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.

like image 90
Ozgur Vatansever Avatar answered Oct 17 '22 08:10

Ozgur Vatansever


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.

like image 40
Marimuthu Avatar answered Oct 17 '22 06:10

Marimuthu