使用storyboard时如何对第一屏的视图控制器进行依赖注入?

mra*_*iao 5 dependency-injection objective-c storyboard ios

手动编写代码时,我们可以通过AppDelegate 中的构造函数注入将依赖项注入到 rootViewController 中:

UIViewController *vc = [[SomeViewController alloc] initWithDependency: dependency];
self.window.rootViewController = vc;
Run Code Online (Sandbox Code Playgroud)

但是,我找不到在使用Storyboard时注入依赖项的方法。将它们注入awakeFromNibviewDidLoad等等似乎是不合适的。

那可以注射吗?

Mar*_*ass 2

在您的 AppDelegate 中测试以下代码:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    let dependency = MyDependency()
    if let firstVC = window?.rootViewController as? MyViewControllerClass {
        firstVC.dependency = dependency
    }

    return true
}
Run Code Online (Sandbox Code Playgroud)