【问题标题】:How to remove KVO observer from tableViewCell?如何从 tableViewCell 中删除 KVO 观察者?
【发布时间】:2015-11-03 05:43:40
【问题描述】:

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

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

【问题讨论】:

    标签: ios swift key-value-observing


    【解决方案1】:

    实现deinit方法并将ignoreFrameChanges()放入其中

    deinit
    {
      ignoreFrameChanges()
    }
    

    在对象被释放之前调用该方法

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多