Crashalot Crashalot - 7 months ago 5
Swift Question

NSNotificationCenter: Add observer but only if not already observing? 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)

Answer

Unfortunately no, there is not. Just like KVO, notification center doesn't provide an API that lets us check whether an observer (self in this case) has already been registered for a notification or not.

Comments