Search code examples
iosswiftobservers

Remove observer from subview


i have a view which has a dropdownmenu as a subview. Right now i am getting an error, when the view is deallocated. "was deallocated while key value observers were still registered with it"

In the views class i am setting the observer:

override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
    self.setNeedsDisplay()
    if keyPath == "frame" {
        // Set up DropdownMenu
        self.dropDownBackground.frame.size.height = self.dropDownMenu.frame.maxY
    }   
}

And adding it to the subview:

dropDownMenu.addObserver(self, forKeyPath: "frame", options: .New, context: nil)

So to avoid the error i am trying to do:

deinit {
    dropDownMenu.removeObserver(self)
}

But the compiler tells me "Cannot invoke 'removeObserver' with an argument list of 'DropDownMenu'"

What am i doing wrong? Thank you!


Solution

  • Have a look at the documentation: the method is called removeObserver(_ observer: NSObject, forKeyPath keyPath: String). So you need to do:

    dropDownMenu.removeObserver(self, forKeyPath: "frame")