Search code examples
iosswiftuitableviewtableviewobservers

Observing Value for TableView


I'm in the process of creating a tableview which changes dynamically in height when the number of cells increases or decreases. In order to complete this, I added an observer to my tableview:

tableView.addObserver(self, forKeyPath: "contentSize", options: .new, context: nil)

I receive this with the following method:

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    tableView.frame = CGRect(x: tableView.frame.origin.x, y: tableView.frame.origin.y, width: tableView.frame.size.width, height: tableView.contentSize.height)
    tableView.reloadData()
}

However, when I run this I get an error:

Thread 1: EXC_BAD_ACCESS (code=2, address=0x7ffeed414ff8)

I am sure these lines are causing the error and have already tried to call super.observeValue(...)

Any help would be greatly appreciated.


Solution

  • The way that Key Value Observing works in Objective C is that EVERY observed change for EVERY object you are observing goes through the same observeValue function. Its entirely possible that your observe function is getting called before the tableView is ever loaded from the storyboard and thats why you are crashing.

    You are supposed to check at least 2 things before you touch the tableView:

    1. is the object parameter === to your tableView (ie is this the object you are looking for)
    2. is the keyPath == to the keyPath that you want to observe on this object?