如何从 uitableViewCell 中删除 KVO 观察器?
How to remove KVO observer from tableViewCell?
我知道这可能不是 MVC 的最佳实践,但我在我的自定义 tableViewCell 中有一个观察者知道我何时展开单元格(下面的代码)。当我按下导航栏上的后退按钮时,应用程序崩溃并显示 "An instance TableViewCell was deallocated while key value observers were still registered with it." 如何检查单元格是否正在观察,以及如何在用户点击后退按钮时删除观察者?非常感谢!!!
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()
}
}
}
实现deinit
方法并在其中放入ignoreFrameChanges()
deinit
{
ignoreFrameChanges()
}
在释放对象之前调用该方法
我知道这可能不是 MVC 的最佳实践,但我在我的自定义 tableViewCell 中有一个观察者知道我何时展开单元格(下面的代码)。当我按下导航栏上的后退按钮时,应用程序崩溃并显示 "An instance TableViewCell was deallocated while key value observers were still registered with it." 如何检查单元格是否正在观察,以及如何在用户点击后退按钮时删除观察者?非常感谢!!!
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()
}
}
}
实现deinit
方法并在其中放入ignoreFrameChanges()
deinit
{
ignoreFrameChanges()
}
在释放对象之前调用该方法