在后退导航中从 Cells 中移除 Observers

Remove Observers from Cells on back navigation

我有一个带单元格的 TableView,我向它们添加了一个 Observer。 我在 willDisplay:

上向 Cell 添加一个 Observer
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    let cell = cell as! CustomCell
    cell.watchFrameChanges()
}

我在 didEndDisplaying 上删除了它:

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

CustomCell 方法:

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")
    }
}

问题是,当我从包含此 TableView 的 ViewController 导航回来时,Observers 没有被删除,我收到此错误:

*** 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.

返回时如何正确移除观察者?

试试这个

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()
        }
    }
}