Search code examples
swiftnsnotificationcenter

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?


Solution

  • 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