使用代理和协议模式发送数据时意外地找到nil

问题描述

我有2个ViewController,firstVC和secondVC。
我想从第一个发送数据,以更新secondVC的变量和UI。
我想在didSelectRowAt中点击tableView的indexPath.row与委托一起发送。
这是我尝试,但选择一排,当应用程序有错误崩溃:
Unexpectedly found nil while implicitly unwrapping an Optional value
我尝试调试,但看到委托为nil,即使我放置了一个使委托firstVC的方法
SecondVC:

func setupDelegate() {
        let FirstVC = storyboard?.instantiateViewController(identifier: "FirstVC") as! FirstVC
        FirstVC.selectionDelegate = self
    }
    
}

extension SecondVC: setSelectionDelegate {
    //this is never executed
    func didChoose(index: Int) {
        lbl.text = String(index)
    }
}

FirstVC:

protocol setSelectionDelegate {
    func didChoose(index: Int)
}

var selectionDelegate: setSelectionDelegate!

override func tableView(_ tableView: UITableView,didSelectRowAt indexPath: IndexPath) {
     let secondVC = UIStoryboard.init(name: "Main",bundle: Bundle.main).instantiateViewController(withIdentifier: "secondVC") as? secondVC
     secondVC?.setupDelegate()
     self.selectionDelegate.didChoose(index: indexPath.row)
}

解决方法

每次显式调用instantiateViewController时,都会得到一个 new 实例的视图控制器实例,这与您在设备/模拟器中看到的实例不同。

使用情节提要剧集(嵌入或模态显示...),您可以使用override prepare(...)功能来引用所需的视图控制器实例。