【问题标题】:Why does it find nil while unwrapping Optional? Xcode 9为什么在展开 Optional 时会发现 nil? Xcode 9
【发布时间】:2018-02-25 09:14:33
【问题描述】:

所以我有一个使用核心数据的表格视图,当我选择一个单元格时,它会转到另一个 VC 并从对应于所选单元格的 CoreData 发送“目标”类项。

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    performSegue(withIdentifier: "toGoalPopup", sender: self)

}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    if segue.identifier == "toGoalPopup" {

        let destinationVC = segue.destination as! goalPopupViewController

        if let indexPath = tableView.indexPathForSelectedRow {

            destinationVC.selectedGoal = goals[indexPath.row]
            print(destinationVC.selectedGoal)

        }
    }
}

此时控制台打印 selectedGoal 的名称、值、添加日期和状态的值,所以我知道它设置正确。

在destinationVC中-

@IBOutlet weak var goalTitleLabel: UILabel!

@IBOutlet weak var goalValueLabel: UILabel!

var selectedGoal: Goal? {
    didSet{
        if let name = selectedGoal?.name {
            goalTitleLabel.text = name
        }
    }
}

我收到“致命错误,在展开 Optional... 时意外发现 nil”消息。

我证明它已经被设置了,它怎么可能是nil?

提前感谢大家的帮助!

【问题讨论】:

    标签: xcode runtime-error


    【解决方案1】:

    这里的nil不是你设置的值,而是goalTitleLabel。您正在设置视图尚未加载时的值(因此 goalTitleLabel 的 IUO 值是 nil)。最好在viewDidLoad 中设置标签的text 属性。

    如果您计划更新发送的对象并更新显示值,那么您需要一个额外的条件来检查isViewLoaded

    您也可以在 prepareForSegue 中调用 loadViewIfNeeded,但恕我直言,这是代码异味。

    【讨论】:

    • 哇,谢谢你的回答。第一次发帖,多谢回复!
    • 很高兴为您提供帮助!如果它解决了您的问题,请不要忘记“接受”(单击向下投票箭头下的复选标记)将来的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多