我正在尝试通过协议从不同的UIViewController调用一个函数,但是我在委托上没有 - 这可能是什么情况?

时间:2016-03-22 23:19:48

标签: ios swift uiviewcontroller delegates protocols

我有两个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

这可能是什么情况?

1 个答案:

答案 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
    }
}