Using Objection with UIViewControllers and Storyboards

Posted on by in Development

I have used Objection in several iOS projects as a lightweight Dependency Injection framework.  If you’re not familiar with it, take a look.  One pain point has been how to inject dependencies for UIViewControllers that are in storyboards.  Your controllers are likely instantiated through segues or by calling instantiateViewControllerWithIdentifier on a storyboard instance.  Wouldn’t it be nice to have Objection inject the declared dependencies from its context on these controllers?  There is a simple way to accomplish this – subclass UIStoryboard and override instantiateViewControllerWithIdentifier.  This technique is based on a stackoverflow post for how another DI framework, Typhoon, can be integrated with storyboards.

The header file is nothing special – just subclassing UIStoryboard

The implementation overrides instantiateViewControllerWithIdentifier and tells Objection to inject dependencies on the new controller before we return it.

Here is an example of using CFStoryboard in an AppDelegate. Once you instantiate the first controller from CFStoryboard, all subsequent controllers will also have the same injecting CFStoryboard instance.

This technique has generally worked well except when our CFStoryboard is not used to instantiate a view controller wired up in a storyboard. For example, I found that controllers wired up as children in Interface Builder’s “Container View” were not created with our CFStoryboard instance. I prefer to manage child controllers programmatically, so this was not a serious problem.

Good luck!