Jaimy
Jaimy

Reputation: 227

setting destinationviewcontroller's label's text in prepareForSegue throws error: unexpectedly found nil while unwrapping Optional value

I am sure the string is not nil and that the label exists, I am trying to find out why the text in the label is nil. The other members of the destinationViewController are getting set correctly , but as soon as I add the line to set the label the program crashes.

// Mark segue
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    // Get reference to the destination view controller
    var detailVC = segue.destinationViewController as! DetailViewController
    var detailImages: Array<UIImage> = []
    detailImages.append(UIImage(named: "pup.jpg")!)
    detailImages.append(UIImage(named: "dog.png")!)
    // Set the property to the selected location so when the view for
    // detail view controller loads, it can access that property to get the feeditem obj
    detailVC.selectedLocation = _selectedLocation;
    println(_str!)
    detailVC.myLabel.text = "hello"
}

Upvotes: 1

Views: 677

Answers (2)

Jaimy
Jaimy

Reputation: 227

Yes, in the end I changed the last line in prepareForSegue to

detailVC.myString = _str as? String

I am not sure if I the the as? since in my detailVC I have added:

var myString:String?

Where would be the best place to convert the NSString to String, or it doesn't matter? Thanks!

Upvotes: 0

Akhilrajtr
Akhilrajtr

Reputation: 5182

This is because the outlet for myLabel will not get set in prepareForSegue, so it will be nil. Try below approach instead,

create a string var in DetailViewController like,

var labelText: String?

in prepareForSegue

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    // Get reference to the destination view controller
    var detailVC = segue.destinationViewController as! DetailViewController
    var detailImages: Array<UIImage> = []
    detailImages.append(UIImage(named: "pup.jpg")!)
    detailImages.append(UIImage(named: "dog.png")!)
    // Set the property to the selected location so when the view for
    // detail view controller loads, it can access that property to get the feeditem obj
    detailVC.selectedLocation = _selectedLocation;
    println(_str!)
    detailVC.labelText = "hello"
}

and in viewDidLoad of DetailViewController

override func viewDidLoad() {
    super.viewDidLoad()

    self.myLabel.text = labelText
    // Do any additional setup after loading the view.
}

Upvotes: 5

Related Questions