rebellion
rebellion

Reputation: 6740

Preparing for segue crashes when instantiating controller

I'm struggling to figure out the error message I get in the prepareForSegue() method. The code that I'm using in this method is the same as in the default Master-Default template in Xcode.

But in my case, this line crashed the application:

let controller = (segue.destinationViewController as! UINavigationController).topViewController as! SummaryViewController

With the following error:

fatal error: unexpectedly found nil while unwrapping an Optional value

I have declared the destination view controller in the top with var summaryViewController: SummaryViewController? = nil and I have a segue from the current view controller to the SummaryViewController, and this tableView:didSelectRowAtIndexPath method:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    performSegueWithIdentifier("showSummary", sender: self)
}

But I have also tried with a segue directly from the tableview cell, (and removing this method), but it still crashes.

Any ideas what I am doing wrong?

Upvotes: 0

Views: 38

Answers (1)

Nitin Gohel
Nitin Gohel

Reputation: 49710

You need to check the VC is nil or not so your prepareForSegue must be like following:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "showSummary"
        {
            if let controller = (segue.destinationViewController as? UINavigationController)!.topViewController as? SummaryViewController
            {
              // write a the code for SummaryViewController
            }
        }
    }

Upvotes: 1

Related Questions