两个视图控制器之间的协议

时间:2016-01-30 14:32:32

标签: ios swift

我想在两个视图控制器之间使用协议。我试过这样:

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()

如何解决此问题?

1 个答案:

答案 0 :(得分:0)

ReceivedPhotosViewController内,你应该设置recievedDelegate。将以下行添加到viewDidLoad

viewWillAppearReceivedPhotosViewController
secondVC.recivedDelegate = self    //assuming secondVC is instance of SecondViewController

所有在调用reloadData时都会检查

if self.recievedDelegate != nil {
    self.recivedDelegate!.reloadData()
}