Crashalot Crashalot - 7 months ago 6
Swift Question

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)

Answer

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.