我想在两个视图控制器之间使用协议。我试过这样:
protocol ReceivedPhotosDelegate{
func reloadData()
}
class SecondViewController: UIViewController {
var recivedDelegate: ReceivedPhotosDelegate?
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.recivedDelegate!.reloadData()
}
}
第二节课:
class ReceivedPhotosViewController: UIViewController,ReceivedPhotosDelegate {
func reloadData() {
print("test ok")
}
}
当我运行此代码时,我收到以下错误:
fatal error: unexpectedly found nil while unwrapping an Optional value
这一行:
self.recivedDelegate!.reloadData()
如何解决此问题?
答案 0 :(得分:0)
在ReceivedPhotosViewController
内,你应该设置recievedDelegate。将以下行添加到viewDidLoad
viewWillAppear
或ReceivedPhotosViewController
secondVC.recivedDelegate = self //assuming secondVC is instance of SecondViewController
所有在调用reloadData时都会检查
if self.recievedDelegate != nil {
self.recivedDelegate!.reloadData()
}