2016-12-13 15 views
0

У меня есть TableView с ячейками, и я добавляю к ним Наблюдателя. я добавить наблюдателя в Cell на willDisplay:Удалить наблюдателей из ячеек на обратной навигации

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

Проблема заключается в том, что, когда я вернуться обратно из моего ViewController, который содержит этот TableView, наблюдатели не удаляются, и я получаю эту ошибку:

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

попробовать это

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