Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSNotificationCenter: Removing an Observer in Swift

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?

like image 885
Jimmery Avatar asked Dec 02 '14 17:12

Jimmery


People also ask

How does removeobserver work in nsnotificationcenter?

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.

What is nsnotificationcenter in Swift?

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.

Can nsnotificationcenter receive messages from non-existing objects?

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.

How do I get notifications from a specific object?

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.


1 Answers

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

like image 63
Mike Pollard Avatar answered Nov 15 '22 23:11

Mike Pollard