简体   繁体   中英

Accessing Data Model in UITabBarController from a Struct

I have an app that uses the UITabBarController and I have a model which I use to pass information between the various Tabs

class BaseTBController: UITabBarController {
  
  var title: String = ""
  var valueData =  Double()

  
  override func viewDidLoad() {
    super.viewDidLoad()
  }

Normally within any of the Tabs in the TabBars, I can just do:

let tabbar = tabBarController as! BaseTBController
let valueData = Int(tabbar.valueData) == 0 ? Int(UserDefaults.standard.double(forKey: UDKeys.valueData)) : Int(tabbar.valueData)

Now, the situation I'm in is like this, I would like to use the data from the Tabbar model data in a helper function (as struct)

Doing this, it doesn't work. Wondering if there is a way to do this and my googling/SO searching skills are just not up to par. TX

struct DataFieldOptions{
  
  static func showValueAs() -> String {
    let tabbar = tabBarController as! BaseTBController
    let valueData = Int(tabbar.valueData) == 0 ? Int(UserDefaults.standard.double(forKey: UDKeys.valueData)) : Int(tabbar.valueData)

    return String(valueData)
  }

This seems a bit of an odd approach. If you are adding a "helper" I would expect you'd have a data-manager class rather than using a var in the tab bar controller.

However, tabBarController is an Optional property of a view controller. If you want to access it from outside the view controller you need to give it a reference.

As a side note, you're showing -> String but you're returning an Int ... I'm going to guess you're really planning on formatting the value as a string in some way, so here's how to do it returning a string:

struct DataFieldOptions{
    static func showValueAs(vcRef vc: UIViewController) -> String {
        // safely make sure we have access to a tabBarController
        //  AND that it is actually a BaseTBController
        if let tbc = vc.tabBarController as? BaseTBController {
            let v = Int(tbc.valueData) == 0 ? Int(UserDefaults.standard.double(forKey: UDKeys.valueData)) : Int(tbc.valueData)
            return "\(v)"
        }
        return ""
    }
}

Then, from a view controller, you would call it like this:

let str = DataFieldOptions.showValueAs(vcRef: self)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM