Trip Trip - 6 months ago 12
Swift Question

My segue is loading my UIViewController, before the last line adds data to it

This error occurred, after I added an extra segue to my UITableView. So that instead of the segue coming from a tableViewCell to my UIViewController, it now comes from the UITableViewController to 2 different UIViewControllers.

I set unique identifiers for both segues

showVerse
and
showAbout
.

The code in my UITableView looks like so :

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if ( indexPath.section == 4 ) {
performSegueWithIdentifier("showAbout", sender: self)
} else {
performSegueWithIdentifier("showVerse", sender: self)
}
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showVerse" {
let pageDetailViewController = segue.destinationViewController as! PageViewController

// Get the cell that generated this segue.
if let selectedCell = sender as? PageTableViewCell {
// ^~~~~~ This line loads my PageViewController for some reason
// Then my PageViewController fails because it doesn't have a `.page`

let indexPath = tableView.indexPathForCell(selectedCell)!
let verse = self.items[indexPath.section][indexPath.row].verse

for page in pages {
if page.valueForKey("chapter") as! Int == indexPath.section + 1 && page.valueForKey("verse") as! Int == verse {


pageDetailViewController.page = page
// ^~~~~ If it could get to this line, then it would have loaded correctly.


}
}

}
} else {
segue.destinationViewController as! AboutController
}

}


When my
indexPath.section
is 0 - 3, it loads my PageViewController before a
.page
is assigned to it.

When my segue is from UITableViewCell to UIViewController, I don't have this issue. It seems to wait all my lines of code to run. And then it would know when my
.page
was set.

Answer

I don't think sender should be self in your performSegueWithIdentifier methods.

I would do something along these lines:

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    let cell = tableView.cellForRowAtIndexPath(indexPath)
    if ( indexPath.section == 4 ) {
        performSegueWithIdentifier("showAbout", sender: cell)
    } else {
        performSegueWithIdentifier("showVerse", sender: cell)
    }   
}
Comments