Reputation: 378
I know this probably isn't best practice for MVC but I have an observer in my custom tableViewCell to know when I am expanded the cell or not (code below). When I press the back button on my nav bar, the app crashes with "An instance TableViewCell was deallocated while key value observers were still registered with it." How can I check if a cell is observing, and how to remove observer when user hits that back button? Thanks a lot!!!
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()
}
}
}
Upvotes: 0
Views: 841
Reputation: 285082
Implement the deinit
method and put ignoreFrameChanges()
in it
deinit
{
ignoreFrameChanges()
}
The method is called before the object will be deallocated
Upvotes: 4