Search code examples
iosswiftuitabbarcontroller

UITabBarController Shared Data Model - share & update model from anywhere


I'm using a TabBarcontroller type app and I'm using a shared model of the form:

enum WorkoutState {
  case Stopped
  case Started
  case Paused
}

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

Currently all is working and I can access and update the variable across the different tabs using

let tabbar = tabBarController as! BaseTBController
if tabbar.workoutState = .Stop {
  //do something
  tabbar.workoutState = .Start
}

Now, the situation is that I seem to need to put this all over the place in my code. eg:

startRun()
resumeRun()
pauseRun()

Is there a better way to do this instead of putting

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

in each of the 3 functions?


Solution

  • You can always use protocol and default extension to achieve what you need

    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
        }
    }
    

    In all you view controller's that has these 3 methods (startRun, resumeRun, pauseRun) simply confirm to this protocol and call updateWorkOutState(to: with appropriate value to modify the status

    class SomeTestViewController: UIViewController {
        func startRun() {
            self.updateWorkOutState(to: .Started)
        }
    
        func resumeRun() {
    
        }
    
        func pauseRun() {
            self.updateWorkOutState(to: .Paused)
        }
    }
    
    extension SomeTestViewController: HandleWorkStateProtocol {}
    

    P.S

    Case values of enum does not follow Pascal casing like Stopped instead it follows Camel casing stopped so change your enum values to

    enum WorkoutState {
      case stopped
      case started
      case paused
    }