How could I inject dependency with custom initializer in UITabBarController?

Viewed 839

I have a custom UITabBarController without any NIB file. The navigation controllers of all modules are created in the viewDidLoad method with creator function. I want to add the coreDataStack with a param via those creator function like this:

override func viewDidLoad() {
super.viewDidLoad()

let aModuleNavCont = aModuleBuilder.createaModule(coreDataStack) as! UINavigationController
...
}

But before this I have to set the coreDataStack property in my own UITabBarController class. I've wrote this init:

init(coreDataStack: CoreDataStack) {
    self.coreDataStack = coreDataStack
    super.init(nibName: nil, bundle: nil)
}

But it said: 'required' initializer 'init(coder:)' must be provided by subclass of 'UITabBarController' Therefore I generated this one with Xcode:

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

Now the build is succeeded, and the app is run well (it looks like well), but I have a hunch it is not soo good solution.

I' tried add super.init(coder: aDecoder) line in the required init, but it said "Property 'self.coreDataStack' not initialized at super.init call".

I've tried several things, but I have no idea, what should I do to handle this well. Could you help with this?

Thank you in advance for any help you can provide.

1 Answers

You are right to be nervous about this, but it is actually correct and the standard way to implement the Coder init when you are not using a NIB.

This barnacle (weird thing that feels glued onto the system) comes from the interaction between Cocoa's highly dynamic nature and Swift's more strict initialization requirements. (Swift added these initialization requirements specifically because of the lessons we learned from ObjC....)

Related