RileyDev
RileyDev

Reputation: 2545

indexPathForSelectedRow returns unexpected nil

I have an array called Objects which are a subclass of NSManagedObject and display their properties in a UITableView.

I have one segue to see the details of the object, which is performed using a gesture - this works fine until I use the prepareForSegue to pass the data of the UITableViewCell to the segueing ViewController. However when using let indexPath = self.table.indexPathForSelectedRow, I am getting a nil value for the selected row so therefore the application crashes when trying to pass the data. Here is an example with the full code:

if segue.identifier == "showDetails" {
    let vc = segue.destinationViewController as! DetailsViewController         
    let indexPath = self.table.indexPathForSelectedRow
    if indexPath == nil { print(index path is NIL")}
    let selectedObject = self.objects[indexPath!.row]   
    vc.setting = setting
    vc.selectedObject = selectedObject          
}

Does anyone know what may be going wrong ? I have done the same thing in another ViewController and it worked fine. Also I was trying to implement another segue for when the cell is selected, but I cannot call prepareForSegue using the function didSelectRowAtIndexPath but can in my other ViewController - I am not sure if this information is relevant or may also indicate what the problem may be.

Upvotes: 0

Views: 1016

Answers (1)

Duncan C
Duncan C

Reputation: 131503

Having no cell selected is a valid condition. You should code defensively to handle that case. You could implement the shouldPerformSegueWithIdentifier: method, and return false if indexPathForSelectedRow returns nil

Upvotes: 3

Related Questions