2015-11-02 71 views
0

我知道这可能不是MVC的最佳实践,但我有一个观察者在我的自定义tableViewCell中以了解何时扩展单元格或不在(代码如下)。当我按下导航栏上的后退按钮时,应用程序崩溃,“一个实例TableViewCell被释放,而关键值观察者仍然注册它。”如何检查单元格是否正在观察,以及如何在用户点击后退按钮时删除观察者?非常感谢!!!如何从tableViewCell中移除KVO观察者?

class ClientDetailTableViewCell: UITableViewCell { 

    // Sets default and expanded cell heights 
    class var expandedHeight:CGFloat { get { return 150 } } 
    class var defaultHeight:CGFloat { get { return 50 } } 

    // sets to check if a row has been clicked 
    var frameAdded = false 

    // checks if height to see if buttons are hidden 
    func checkHeight() { 

     button1.hidden = (frame.size.height < PersonTableViewCell.expandedHeight) 
    } 

    // Start Key Value Observing 
    func watchFrameChanges() { 

     if(!frameAdded) { 

     addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions.New, context: nil) 
     frameAdded = true 
     } 
    } 

    // Stop Key Value Observing Changes 
    func ignoreFrameChanges() { 

     if(frameAdded) { 

     removeObserver(self, forKeyPath: "frame") 
     frameAdded = false 
     } 
    } 

    // If the observer adds keypath for "frame", run checkHeight() 
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { 

     if keyPath == "frame" { 

     checkHeight() 
     } 
    } 
} 

回答

4

落实deinit方法,并把ignoreFrameChanges()

deinit 
{ 
    ignoreFrameChanges() 
} 

的方法被调用的对象将被释放

+0

之前,我需要的,感谢您的帮助! – tahoecoop