I have a view controller with a button. When the button is pressed it adds an observer, like so:
func buttonPress(sender:UIButton){
NSNotificationCenter.defaultCenter().addObserverForName("buttonPressEvent", object:nil, queue:nil, usingBlock:{(notif) -> Void in
// code
})
}
When I dismiss this view controller, and then return to it and press the button the //code
is executed twice. If I go away and come back again the //code
is executed three times, and so on.
What I want to do is to remove the Observer before I add it again, so this code doesn't execute twice. Ive gone through the documentation here and Ive added this line of code just above where I add the Observer:
NSNotificationCenter.defaultCenter().removeObserver(self, name:"buttonPressEvent", object:nil)
But this isnt working.
Can anyone tell me where I'm going wrong?
So NSNotificationCenter keeps a "dispatch table" of all observers registered to be notified when a given key is "posted" to. When removeObserver is called, it removes all entries in that dispatch table related to the observer you specify.
NSNotificationCenter is particularly useful when there are multiple class or struct instances that need to take action based on something that happens elsewhere in your application. For this type of scenario, NSNotificationCenter can be a great tool to wield as you develop apps in Swift for iOS.
NSNotificationCenter is great if there are listeners for its notifications, but if a controller or other object doesn't exist yet, it obviously can't receive messages... I don't suppose a non-existent thing would care though.
Objects register with a notification center to receive notifications ( NSNotification objects) using the addObserver:selector:name:object: or addObserverForName:object:queue:usingBlock: methods. When an object adds itself as an observer, it specifies which notifications it should receive.
When you use the 'blocks' based approach to observing notifications then self
isn't in fact the observer. The function returns an object which acts as the observer:
func addObserverForName(_ name: String?,
object obj: AnyObject?,
queue queue: NSOperationQueue?,
usingBlock block: (NSNotification!) -> Void) -> NSObjectProtocol
You need to keep a reference to this returned object and pass it in as the observer when you call removeObserver
It's explained well in the Apple Doc here
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