我有两个UIViewControllers。
第一个包含一个默认可见的容器,该类看起来像这样:
protocol HandleMapPopupBehavior {
func hideContainer()
}
class MapEvents: UIViewController, HandleMapPopupBehavior {
@IBOutlet weak var userDetails: UIView!
var userProfile: YourFullUser?
override func viewDidLoad() {
super.viewDidLoad()
userProfile = YourFullUser()
}
func hideContainer(){
userDetails.hidden = true
print("hiding container now")
}
}
第二个包含应调用hideContainer()
中的函数viewDidAppear()
的调用:
class YourFullUser: UIViewController{
var delegate: HandleMapPopupBehavior?
override func viewDidAppear(animated: Bool) {
super.viewWillAppear(animated)
delegate!.hideContainer() //this line causes error
print("container should be hidden")
}
但是现在当我运行这个ViewController时,我收到了错误:
fatal error: unexpectedly found nil while unwrapping an Optional value
这可能是什么情况?
答案 0 :(得分:1)
使您的协议符合class
protocol HandleMapPopupBehavior: class {
func hideContainer()
}
当您创建YourFullUser
为其代理人分配self
时:
class MapEvents: UIViewController, HandleMapPopupBehavior {
var userProfile: YourFullUser?
override func viewDidLoad() {
super.viewDidLoad()
userProfile = YourFullUser()
userProfile?.delegate = self
}
func hideContainer() {
print("hiding container now")
}
}
YourFullUser类:
class YourFullUser: UIViewController {
weak var delegate: HandleMapPopupBehavior?
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
delegate?.hideContainer() // Safely use the delegate
}
}