johnniexo88 johnniexo88 - 4 months ago 13
iOS Question

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?

Answer

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.