在Swift中的标签和VC之间共享数据

问题描述

我有一个带有自定义标签栏控制器的应用程序,以及一个由stateController支持的数据模型。我想在标签之间共享模型中的数据。

少量标注:

  • 我的应用同时使用情节提要和程序化(Swift 5)。在此处使用情节提要
  • 在加载应用程序时,我检查userDefaults以查看它是否是首次启动。如果是,则firstTimeVC是rootVC
  • 如果不是,则我的选项卡栏是rootVC。这种逻辑存在于场景委托中

我正在使用Dependency Injection在各个选项卡之间创建我的数据模型的共享实例。人们建议使用App / Scene Delegate将数据模型注入到我的TabBar和childVC中。问题是,TabBar并不总是rootVC。​​

我的问题是:

  • 我可以直接从TabBar将数据模型注入TabBar的子VC吗?代替场景委托吗?
  • 如果我使用Scene Delegate,那么当TabBar不是rootVC(即首次启动应用程序)时,如何将数据模型注入TabBar的childVCs中?
  • 或者TabBar应该始终是rootVC,我将首次启动检查移至childVC而不是Scene Delegate
  • 什么是正确的方法

我第一次进行应用启动检查(当前在Scene Delegate中):

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

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

我的依赖项注入(当前在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)
    }
}

我的情节提要和VC设置的屏幕截图:

Screenshot of my storyboard & VC setup

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)