0

I have an app with a custom tab bar controller, and a data model powered by a stateController. I want to share data from my model across the tabs.

Few callouts:

  • My app uses both storyboards & programmatic (Swift 5). Assume storyboard here
  • When the app loads, I check userDefaults to see if it's the first app launch. If it is, firstTimeVC is the rootVC
  • If it's not, my Tab Bar is the rootVC. And this logic lives in the Scene Delegate

I'm using Dependency Injection to create a shared instance of my data model across tabs. People suggest injecting the data model into my TabBar & childVCs using the App / Scene Delegate. Problem is, the TabBar isn't always the rootVC.

My questions are:

  • Can I inject my data model into the TabBar's child VCs directly from the TabBar? Instead of the Scene Delegate?
  • If I use Scene Delegate, then how do I inject the data model into the TabBar's childVCs when the TabBar is NOT the rootVC (ie first app launch)
  • Or should the TabBar always be the rootVC, and I move the first-launch-check to a childVC instead of Scene Delegate
  • What's the right way to do this?

My first time app launch check (currently inside Scene Delegate):

  if isFirstLaunch {
     rootViewController = "FirstTimeUserViewController"
  } else {
     rootViewController = "TabBarController"
  }

window?.rootViewController = rootViewController
window?.makeKeyAndVisible()

My dependency injection (currently inside Scene Delegate):

let tabBarController = storyboard.instantiateViewController(withIdentifier: "CustomTabBarController") as! CustomTabBarController
for child in tabBarController.viewControllers ?? [] {
    if let top = child as? StateControllerProtocol {
        top.setStateController(stateController: stateController)
    }
}

A screenshot of my storyboard & VC setup:

Screenshot of my storyboard & VC setup

theogood
  • 85
  • 1
  • 1
  • 7
  • why not create the data model in the app delegate and access it with a singleton? – john elemans Oct 08 '20 at 04:41
  • singleton's generally make code less re-usable. and increase coupling and dependency between my VCs, App Delegate and models. they're considered an 'anti-pattern' in Swift for this reason: https://stackoverflow.com/q/12755539/13551385 – theogood Oct 08 '20 at 12:38
  • In this case your data model is already a global and, as you describe it, already creates a coupling between VCs. Singletons should be avoided when they cause coupling, not when it's already there. VCs are already almost never reusable with different data anyway. – john elemans Oct 09 '20 at 17:10

0 Answers0