1

I'm trying to create my first iOS app

I got this error "unexpectedly found nil while unwrapping an Optional value" when I try to access variable from my delegate view controller

I'm trying to get a pressed cell value to be set as label text on my target controller

This is the first controller

class SearchStationViewController: UITableViewController, writeValueBackDelegate {
    var selectedStation: String!
    var fromStationValue: String! = "None"

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        selectedStation = stations[indexPath.row].StationName
        fromStationValue = selectedStation

        let vc = SelectedStationViewController()
        vc.fromStationValue = self.fromStationValue
        vc.delegate = self

        self.dismissViewControllerAnimated(true, completion: nil)
    }
}

And the target controller which I would like it's label.text to be changed

protocol writeValueBackDelegate {
    var fromStationValue: String! {get set}
}

class SelectedStationViewController: UITableViewController {
    @IBOutlet weak var stationFrom: UILabel!
    var delegate: writeValueBackDelegate! = nil
    var fromStationValue: String! = "None"

    override func viewDidLoad() {
        super.viewDidLoad()

        stationFrom.text = fromStationValue        
    }
}
StereoNight
  • 31
  • 1
  • 4
  • 2
    What is the error *exactly*? Your question lacks some detail. I presume you have to instantiate your View Controller from the storyboard and not directly and your IBOutlet is nil. – Sebastian Wramba Nov 05 '14 at 12:11
  • The error shows as "unexpectedly found nil while unwrapping an Optional value" while I was trying to set the label 'stationFrom' to the new value 'fromStationValue' retrieved from first viewcontroller. Sorry for being unclear – StereoNight Nov 05 '14 at 13:48
  • I can't figure out your view hierarchy. Is `SearchStationViewController` shown first and then `SelectedStationViewController` shown when a station is selected? The way you have it now, the delegate/protocol is used to pass data from `SelectedStationViewController` to `SearchStationViewController`, not the other way around. – Ron Fessler Nov 05 '14 at 16:00

1 Answers1

3

So I'll just refer to answer I gave earlier this day: Flappy Bird Coding Error in Swift

You will have to initialize your controller with the corresponding xib oder storyboard. Example:

let storyboard = UIStoryboard(name: "myStoryboardName", bundle: nil);
let vc = storyboard.instantiateViewControllerWithIdentifier("myVCID") as UIViewController;

(from Instantiate and Present a viewController in Swift)

Otherwise your view controller will not know any outlets and they will be nil.

Community
  • 1
  • 1
Sebastian Wramba
  • 10,087
  • 8
  • 41
  • 58