Search code examples
iosswiftuitableviewobservers

Remove Observers from Cells on back navigation


I have a TableView with Cells and I add an Observer to them. I add an Observer to Cell on willDisplay:

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    let cell = cell as! CustomCell
    cell.watchFrameChanges()
}

I remove it on didEndDisplaying:

func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    let cell = cell as! CustomCell
    cell.unwatchFrameChanges()
}

CustomCell methods:

func watchFrameChanges() -> Void {
    self.addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions.new, context: nil)
}

func unwatchFrameChanges() -> Void {
    if self.observationInfo != nil {
        self.removeObserver(self, forKeyPath: "frame")
    }
}

The problem is that when I navigate back from my ViewController that contains this TableView, Observers are not removed and I get this error:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'An instance 0x7f892d216800 of class MyProject.CustomCell was deallocated while key value observers were still registered with it.

How to properly remove Observers when navigating back?


Solution

  • try this

    override func viewWillDisappear(animated: Bool) {    
        super.viewWillDisappear(animated)
        for row in 0...(array.count-1) {
            let indexPath = NSIndexPath(forRow: row, inSection: 0)
            if let cell = tableView.cellForRowAtIndexPath(indexPath) as? CustomCell {
                cell.unwatchFrameChanges()
            }
        }
    }