Search code examples
ios8scene

Passing data between scenes


I'm trying to set the label text in scene 2 from scene 1. I wrote the following code.

// original viewController (scene 1)
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
         let destination = segue.destinationViewController as Scene2ViewController
            destination.scene2Label.text = "Arrived from scene 1"
        } //scene2Label is a Label in Scene2ViewController

This throws an error saying: unexpectedly found nil while unwrapping an Optional value. It is poinitng to

destination.scene2Label.text = "Arrived from scene 1"

How is that possible? I thought I set the text value of scene2Label to "Arrived from scene 1".

On the other hand, this this code work just fine:

class ViewController: UIViewController {
    @IBOutlet weak var scene1Label: UILabel!
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        let destination = segue.destinationViewController as Scene2ViewController
        destination.labelText = "Arrived from scene 1"
    }
}

class Scene2ViewController: UIViewController {
    @IBOutlet weak var scene2Label: UILabel!
    var labelText : String?

    override func viewDidLoad() {
        super.viewDidLoad()
        scene2Label.text = labelText
    }
}

Why?


Solution

  • The destination controller that you get during prepareForSegue: has not loaded its view at that time. That also means that none of its outlets for subviews have been connected yet.

    The earliest that you can be sure of having outlets is viewDidLoad.