Right now the API doesn't seem to provide a way to detect if an observer has already been added for a particular NSNotification. What's the best way to avoid adding multiple NSNotification observers other than maintaining a flag on your end to keep track? Has anyone already created a category to facilitate this?
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.
An object containing information broadcast to registered observers that bridges to Notification ; use NSNotification when you need reference semantics or other Foundation-specific behavior.
A distributed notification center delivers notifications between applications. In this case, the notification object must always be a CFString object and the notification dictionary must contain only property list values.
One way to prevent duplicate observers from being added is to explicitly call removeObserver for the target / selector before adding it again. I imagine you can add this as a category method:
@interface NSNotificationCenter (UniqueNotif) - (void)addUniqueObserver:(id)observer selector:(SEL)selector name:(NSString *)name object:(id)object { [[NSNotificationCenter defaultCenter] removeObserver:observer name:name object:object]; [[NSNotificationCenter defaultCenter] addObserver:observer selector:selector name:name object:object]; } @end
This assumes that the you will only add one unique observer to each target for any notification name, as it will remove any existing observers for that notification name.
import Foundation extension NotificationCenter { func setObserver(_ observer: Any, selector: Selector, name: Notification.Name, object: Any?) { removeObserver(observer, name: name, object: object) addObserver(observer, selector: selector, name: name, object: object) } }
Swift 3-4:
import Foundation extension NotificationCenter { func setObserver(_ observer: AnyObject, selector: Selector, name: NSNotification.Name, object: AnyObject?) { removeObserver(observer, name: name, object: object) addObserver(observer, selector: selector, name: name, object: object) } }
Swift 2:
import Foundation extension NSNotificationCenter { func setObserver(observer: AnyObject, selector: Selector, name: String?, object: AnyObject?) { removeObserver(observer, name: name, object: object) addObserver(observer, selector: selector, name: name, object: object) } }
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