我有一个带有单元格的TableView,我向它们添加了一个Observer。 我在willDisplay上添加了一个Observer给Cell:
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.
如何在导航时正确删除观察者?
答案 0 :(得分:0)
试试这个
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()
}
}
}