UITabBarController 共享数据模型 - 从任何地方共享和更新模型

UITabBarController Shared Data Model - share & update model from anywhere

我正在使用 TabBarcontroller 类型的应用程序,并且我正在使用以下形式的共享模型:

enum WorkoutState {
  case Stopped
  case Started
  case Paused
}

class BaseTBController: UITabBarController {
  var workoutState: WorkoutState? = .Stopped
}  

目前一切正常,我可以使用

访问和更新不同选项卡中的变量
let tabbar = tabBarController as! BaseTBController
if tabbar.workoutState = .Stop {
  //do something
  tabbar.workoutState = .Start
}

现在的情况是,我似乎需要将它放在代码中的所有位置。例如:

startRun()
resumeRun()
pauseRun()

有没有更好的方法来代替

let tabbar = tabBarController as! BaseTBController
tabbar.workoutState = .Start

在这 3 个函数中?

您始终可以使用协议和默认扩展名来实现您的需要

protocol HandleWorkStateProtocol where Self: UIViewController {
    func updateWorkOutState(to: WorkoutState)
}

extension HandleWorkStateProtocol {
    func updateWorkOutState(to state: WorkoutState) {
        guard let tabBarController = self.tabBarController as? BaseTBController else { return }
        tabBarController.workoutState = state
    }
}

在所有具有这 3 个方法(startRun、resumeRun、pauseRun)的视图控制器中,只需确认此协议并使用适当的值调用 updateWorkOutState(to: 来修改状态

class SomeTestViewController: UIViewController {
    func startRun() {
        self.updateWorkOutState(to: .Started)
    }

    func resumeRun() {

    }

    func pauseRun() {
        self.updateWorkOutState(to: .Paused)
    }
}

extension SomeTestViewController: HandleWorkStateProtocol {}

P.S

枚举的大小写值不像 Stopped 那样遵循 Pascal 大小写,而是遵循 Camel 大小写 stopped 所以将枚举值更改为

enum WorkoutState {
  case stopped
  case started
  case paused
}