我在 Swift 中有一个奇怪的问题。
它与在视图控制器之间传递数据的其他问题有关,但这里的区别在于,它旨在传递从“didSelectRowAt”方法加载的简单对象。
选择行时,我正在从表视图控制器传递数据。数据作为对象传递,我可以打印数据并在委员会中查看它但是当我尝试从中分配值时,我得到了可怕的:'在隐式展开可选值时意外发现 nil' 错误。不知道我在这里错过了什么!
从表视图控制器 A:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "existingStudentSegue", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let destinationVC = segue.destination as! StudentDetailTableViewController
if let indexPath = tableView.indexPathForSelectedRow {
destinationVC.selectedStudent = studentsArray?[indexPath.row]
}
}
由 Table View Controller B 接收:
var selectedStudent: Students? {
didSet {
print("DATA RECEIVED: \(String(describing: selectedStudent))")
print("DATA TYPE: \ (type(of: selectedStudent))")
firstNameText.text = selectedStudent?.firstName
}
}
“打印”语句显示我输入的测试数据,“类型”显示我设置的学生类,如下所示。
DATA RECEIVED: Optional(Students {created = 2019-09-24 12:07:23 +0000; name = Anna Altitude; ...(it's all here)
DATA TYPE: Optional<Students>
当我尝试在表视图控制器 B 的文本字段中显示文本时,代码失败。我在调用堆栈中看到 selectedStudent 的数据为空白。但怎么可能呢?该对象已填充且可访问。