didDeselectRowAtIndexPath indexPath is nil
Asked Answered
A

0

0

I have a TableViewController which implements the TableViewDelegate methods:

public override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    let cell = tableView.cellForRowAtIndexPath(indexPath) as! ParticipantesSearchTableViewCell
    cell.viewModel?.active = true
}

public override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
    let cell = tableView.cellForRowAtIndexPath(indexPath) as! ParticipantesSearchTableViewCell
    cell.selectedStateImageView.hidden = true
    cell.viewModel?.active = false
}

Please note that I never remove nor set my tableView.editing to true. Also, my numberOfRowsInSection method never changes.

If I set my tableView to tableView.allowsSingleSelection = true I can select and deselect cells just fine and the above methods fire as aspected. However, when I scroll on my tableView and select a new cell the method didDeselectRowAtIndexPath crashes on let cell = tableView.cellForRowAtIndexPath(indexPath) as! ParticipantesSearchTableViewCell

At this point I debugged tableView.indexPathForSelectedRow and it returns nil.

Any idea what I'm implementing wrong here or if this is a bug? Because I try to use the same table with tableView.allowsMultipleSelection = true and I can select, deselect, and scroll just fine.

Almeta answered 26/4, 2016 at 20:27 Comment(4)
Verify that indexPath (not tableView.indexPathForSelectedRow) in didDeselectRowAtIndexPath is non-nil. It's also possible the forced downcast to ParticipantesSearchTableViewCell is causing the crash.Burnsides
The thing is that the cell may not be visible and cells are reused. So it may be nil. Clearly, you should change the datasource, and in tableView:cellForRowAtIndexPath: hide/unhide the imageView, or just override also the ParticipantesSearchTableViewCell select method to show/hide the image.Laquanda
Try printing indexPath. Maybe the table is nil. IndexPath is not an optional; it cannot be nilLifeboat
This confusion had a lot to do with my understanding of how selection in a tableview worked. I followed @Laquanda advice and change my viewModel layer. Thanks a lot to everyone who helpedAlmeta

© 2022 - 2024 — McMap. All rights reserved.