gpt4 book ai didi

ios - 两个 View Controller 之间的协议(protocol)

转载 作者:行者123 更新时间:2023-11-30 13:44:47 25 4
gpt4 key购买 nike

我想在两个 View Controller 之间使用协议(protocol)。我尝试过这样的:

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

如何解决这个问题?

最佳答案

ReceivedPhotosViewController内,您应该设置receivedDelegate。将以下行添加到 ReceivedPhotosViewController

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

在调用 reloadData 时都进行 nil 检查

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

关于ios - 两个 View Controller 之间的协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35102998/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com