Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do dependency injection for the view controller of the first screen when using storyboard ?

When writing code manually, we could inject dependencies to rootViewController by constructor injection in AppDelegate:

UIViewController *vc = [[SomeViewController alloc] initWithDependency: dependency];
self.window.rootViewController = vc;

However, I can not find a way to inject dependencies when using Storyboard. It seems inappropriate to inject them in awakeFromNib or viewDidLoad etc.

Is that possible to inject them ?

like image 741
mrahmiao Avatar asked Nov 11 '22 02:11

mrahmiao


1 Answers

In your AppDelegate test the following code:

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

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

    return true
}
like image 78
MarMass Avatar answered Nov 14 '22 21:11

MarMass