johnniexo88
johnniexo88

Reputation: 313

Variable nil when trying to pass variable to view controller with segue

Here is the code I currently have:

var valueToPass:String!

func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
    let indexPath = tableView.indexPathForSelectedRow();
    let currentCell = tableView.cellForRowAtIndexPath(indexPath!) as UITableViewCell!;

    valueToPass = currentCell.textLabel.text // valueToPass now equals "test"
    performSegueWithIdentifier("yourSegueIdentifer", sender: self)

}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    var viewController = segue.destinationViewController as AnotherViewController
    viewController.passedValue = valueToPass // valueToPass equals nil here? Why?
}

as you can see, i have assigned "test" to valueToPass in didSelectRowAtIndexPath but in prepareForSegue, valueToPass is nil? why?

Upvotes: 1

Views: 676

Answers (1)

Tob
Tob

Reputation: 1025

Try replacing:

func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
    let indexPath = tableView.indexPathForSelectedRow();
    let currentCell = tableView.cellForRowAtIndexPath(indexPath!) as UITableViewCell!;

    valueToPass = currentCell.textLabel.text // valueToPass now equals "test"
    performSegueWithIdentifier("yourSegueIdentifer", sender: self)

}

With this:

func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {

    let currentCell = tableView.cellForRowAtIndexPath(indexPath.row) as! UITableViewCell;

    valueToPass = currentCell.textLabel.text! // valueToPass now equals "test"
    performSegueWithIdentifier("yourSegueIdentifer", sender: self)

}

Also, when you made the segue in the storyboard, make sure you DID NOT drag from the tableview to the next viewcontroller. This is because if you do this automatically, then perform segue will be called BEFORE didSelectRow... making it perform the segue before you set the value. Just drag from the viewcontroller that hosts the table view to the new view.

Upvotes: 1

Related Questions