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

问题描述

我使用的是 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 {}

附注

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

enum WorkoutState {
  case stopped
  case started
  case paused
}