Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(Swift) PrepareForSegue: fatal error: unexpectedly found nil while unwrapping an Optional value

DetailViewController:

    @IBOutlet var selectedBundesland: UILabel!

TableViewController:

    override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {


    if (segue.identifier == "BackToCalculator") {
        var vc:FirstViewController = segue.destinationViewController as FirstViewController
            vc.selectedBundesland.text = "Test"
    }

IBOutlet is connected!

Error: fatal error: unexpectedly found nil while unwrapping an Optional value

I read multiple pages about Optionals but i didn't know the answer to my problem.

Do you need more information about my project?

like image 800
Velocity Avatar asked Aug 21 '14 09:08

Velocity


3 Answers

You cannot write directly to the UILabel in prepareForSegue because the view controller is not fully initialised yet. You need to create another string property to hold the value and put it into the label in the appropriate function - such as viewWillAppear.

like image 76
Paulw11 Avatar answered Oct 13 '22 07:10

Paulw11


DetailViewController:

var textValue: String = ""
@IBOutlet weak var selectedBundesland: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()
    selectedBundesland.text = textValue
}

TableViewController:

     if (segue.identifier == "BackToCalculator") {  
         var vc:FirstViewController = segue.destinationViewController as FirstViewController
         vc.textValue = "Test"
}
like image 23
BeomGeun Lee Avatar answered Oct 13 '22 07:10

BeomGeun Lee


Recently had this problem. The problem was that I had dragged the segue from a specific object from my current view controller to the destination view controller - do not do this if you want to pass values.

Instead drag it from the yellow block at the top of the window to the destination view controller. Then name the segue appropriately.

Then use the if (segue.identifier == "BackToCalculator") to assign the value as you are currently. All should work out!

like image 5
Josh Avatar answered Oct 13 '22 07:10

Josh