通过初始化器(使用Storyboard)注入依赖项? [迅速]

时间:2016-12-17 12:58:41

标签: swift dependency-injection initialization uistoryboard

我想知道是否有办法不通过setter明确地传递你的依赖对象。即setter依赖项:

var store: Store!

这可以通过VC的初始化程序(instantiateViewControllerWithIdentifier)以某种方式完成,即初始化程序注入故事板吗? 感谢

1 个答案:

答案 0 :(得分:0)

您可以引入一个额外的类,负责配置您的viewController。

class MyViewControllerConfigurator {

    static func configure(viewController: MyViewController) {

        let someDependency = SomeDependency()

        viewController.someDependency = someDependency

        // force trigger lazy initialization of view (and subviews), which would be nil otherwize in awaikFromNib
        _ = viewController.view

        // do further configuration here (add child view controller, set delegates ...)
    }
}

MyViewController中的用法:

class MyViewController: UIViewController {

    override func awakeFromNib() {
        super.awakeFromNib()
        MyViewControllerConfigurator.configure(viewController: self)
    }
}

这样,即使使用Storyboard实例化,viewController也会被配置。