Storyboards make dependency injection of view controllers challenging, because they insist on instantiating the view controllers internally. This restriction can be worked around by subclassing UIStoryboard and overriding the -instantiateViewControllerWithIdentifier:
method to perform configuration work immediately following the instantiation. The same storyboard instance that is used to create the initial view controller will be used to instantiate further view controllers accessed via segues.
This pod provides a BlindsidedStoryboard
subclass of UIStoryboard which exemplifies this technique, integrating with the Blindside DI framework. It includes a small sample app demonstrating how this could be used.
The BlindsidedStoryboard(CrossStoryboardSegues) category can be included to allow for seamless integration with Cross Storyboard Segues
When you create a storyboard instance to show a view controller, just do it like this:
id injector = [Blindside injectorWithModule:[[MyBlindsideModule alloc] init]];
UIStoryboard *storyboard = [BlindsidedStoryboard storyboardWithName:@"Main" bundle:nil injector:self.injector];
UIViewController *viewController = [storyboard instantiateInitialViewController];
BlindsidedStoryboard
will ensure that viewController has its dependencies injected before it is returned to you. Note that, because the storyboard instantiates the view controller via -initWithCoder:
, it is necessary to use -bsProperties
to specify the class' dependencies. Also keep in mind that the dependencies won't be available until after -awakeFromNib
has been called.
BlindsidedStoryboard is available through CocoaPods. To install it, simply add the following line to your Podfile:
pod "BlindsidedStoryboard"
Brian Croom, brian.s.croom@gmail.com
BlindsidedStoryboard is available under the MIT license. See the LICENSE file for more info.