Mehmet Mehmet - 3 months ago 16
iOS Question

Passing object with prepareForSegue Swift

I am trying to pass an object to another scene with prepareForSegue()

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
var nextScene = segue.destinationViewController as! VehicleDetailsTableViewController

// Pass the selected object to the new view controller.
if let indexPath = self.tableView.indexPathForSelectedRow() {
let selectedVehicle = vehicles[indexPath.row]
nextScene.currentVehicle = selectedVehicle
}
}


And I have currentVehicle object to catch these object. But, when I try to run, it brokes and get error about downcasting.

Error EDIT


Could not cast value of type 'XXX.DisplayViewController'
(0x1082dcd80) to 'XXX.VehicleDetailsTableViewController'
(0x1082dc9a0). (lldb)

Answer

You have to give the segue an identifier in the storyboard.(say mySegue)

 override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?){....}

Is called for all segues being called form your current UIViewController. So the identifer is to differentiate the different segues

Then use this code:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "mySegue" {
    var nextScene =  segue.destinationViewController as! VehicleDetailsTableViewController

    // Pass the selected object to the new view controller.
    if let indexPath = self.tableView.indexPathForSelectedRow() {
        let selectedVehicle = vehicles[indexPath.row]
        nextScene.currentVehicle = selectedVehicle
    }
  }
}

Place a break point after var nextScene and see if it is being triggered on clicking any cell in the TableView. If it isn't then the identifier name u provided in the storyboard must be different then the one given here.

Comments