prepare(for segue: )
函数运行,但是数据没有发送到我的目标ViewController。加载必须接收数据的VC的集合视图时,出现以下错误:
在展开可选值时意外发现nil
我已经确认segue类型是 selection
segue,segue标识符正确,并且视图可以显示伪数据。
第一视图控制器(DrawerVC):
let realm = try! Realm()
var allDrawers: Results<Drawer>?
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("goToTool segue")
performSegue(withIdentifier: "goToTool", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "goToTool" {
print("Prepare for segue from drawerVC ran") // this runs!
let destinationVC = segue.destination as! ToolVC
if let indexPath = tableView.indexPathForSelectedRow {
destinationVC.selectedDrawer = allDrawers?[indexPath.row]
print("Selected drawer set to index path") // doesn't run :(
}
} else if segue.identifier == "goToEditCategory" {
_ = segue.destination as! EditCategoryVC
}
}
目标视图控制器(ToolVC):
let realm = try! Realm()
var allTools: Results<Tool>?
var selectedDrawer: Drawer? {
didSet{
// doesn't run since selectedDrawer was never set :(
print("The selected drawer changed from \(oldValue) to \(selectedDrawer?.title)")
loadTools()
}
}
func loadTools() {
allTools = selectedDrawer?.tools.sorted(byKeyPath: "title", ascending: false)
toolCollectionView.reloadData() // this is where I get the optional value error
}
答案 0 :(得分:1)
您犯了一个非常常见的错误。
在目标视图控制器中,您正在访问loadTools()
中的表视图,该表视图在您分配所选抽屉时尚未连接。因此,表视图为nil
并导致崩溃。
一种解决方案是删除didSet
观察者
var selectedDrawer: Drawer?
并将数据加载到viewDidLoad
func viewDidLoad() {
super.viewDidLoad()
if let drawer = selectedDrawer {
allTools = drawer.tools.sorted(byKeyPath: "title", ascending: false)
toolCollectionView.reloadData()
}
}
如果将Segue从单元格连接到目标视图控制器,则删除didSelectRowAt
方法。