【问题标题】:Swift - unexpectedly found nil while unwrapping an Optional value - calling variable from delegateSwift - 在展开可选值时意外发现 nil - 从委托调用变量
【发布时间】:2014-11-05 12:07:16
【问题描述】:

我正在尝试创建我的第一个 iOS 应用

当我尝试从我的委托视图控制器访问变量时,出现此错误“在展开可选值时意外发现 nil”

我正在尝试将按下的单元格值设置为目标控制器上的标签文本

这是第一个控制器

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)
    }
}

以及我希望更改 label.text 的目标控制器

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        
    }
}

【问题讨论】:

  • 究竟的错误是什么?你的问题缺乏一些细节。我认为您必须从情节提要而不是直接实例化您的视图控制器,并且您的 IBOutlet 为零。
  • 当我试图将标签“stationFrom”设置为从第一个视图控制器检索到的新值“fromStationValue”时,错误显示为“在展开可选值时意外发现 nil”。抱歉不清楚
  • 我无法弄清楚您的视图层次结构。选择电台时是否先显示SearchStationViewController,然后显示SelectedStationViewController?按照您现在的方式,委托/协议用于将数据从 SelectedStationViewController 传递到 SearchStationViewController,而不是相反。

标签: ios swift delegates null optional-values


【解决方案1】:

所以我只参考我今天早些时候给出的答案:Flappy Bird Coding Error in Swift

您必须使用相应的 xib oder 故事板来初始化您的控制器。示例:

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

(来自Instantiate and Present a viewController in Swift

否则您的视图控制器将不知道任何出口,它们将为零。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-22
    • 2015-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多