Nirri Nirri - 4 months ago 55
Swift Question

rectForRowAtIndexPath crashing with defined indexPath in UITableView

The following code is crashing at


currentCellRect = tableView.rectForRowAtIndexPath(indexPaths[0])


But only sometimes.

public func showCellScrollCount(animated:Bool) {
self.tableView.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.New, context: nil)
self.tableView.addObserver(self, forKeyPath: "dragging", options: NSKeyValueObservingOptions.New, context: nil)
}

override public func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
switch (keyPath, object) {

case (.Some("contentOffset"), _):
self.updateScrollPosition()
default:
super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
}
}

func updateScrollPosition() {

let indexPaths = tableView.indexPathsForVisibleRows
var currentCellRect:CGRect?
if let indexPaths = indexPaths {
if indexPaths.count > 0 {
currentCellRect = tableView.rectForRowAtIndexPath(indexPaths[0])
scrollCountView.currentScrollCountNum = indexPaths[0].row
}
}
}


It crashes with "BAD_ACCESS". Does anyone have any idea why?

enter image description here

enter image description here

...

enter image description here

EDIT: Is it possible it's happening because I'm calling tableView.reloadData() right before I add observers, and the call isn't finished yet?

Answer

Updated

Your code works fine since I added it to my tableView controller and called showCellScrollCount func once. Where you call showCellScrollCount, do you call it multiple times? It can be problem if so.

Update 3

here is the problem:

public var totalScrollCountNum = 0 {
    didSet {
        scrollCountView.totalScrollCountNum = totalScrollCountNum
        showCellScrollCount(false)
    }
}

move showCellScrollCount(false) to initializers