How to access data in Class globally in any ViewController in the project

前端 未结 2 1093
误落风尘
误落风尘 2020-12-02 03:07

I am a newbie in Swift.

Objective: Access the data globally

How to use Swift to implement a global Temporary storage using below class to store data

<
2条回答
  •  一向
    一向 (楼主)
    2020-12-02 03:41

    You can follow the step. How to set shared variable in Swift 3

    1. Create a model file "TimetableModel.swift"

      import Foundation
      class TimetableModel {
          static let sharedInstance = TimetableModel()
          let categories:[Day]        
          var user_id = Int()
          // define any variable here
      }
      
    2. After that create any controller

      import UIKit
      class TimetableVC: UIViewController {
          override func viewDidLoad() { // now you can access shared variable  
              TimetableModel.sharedInstance.categories[section].name    TimetableModel.sharedInstance.user_id
          }
      }
      

提交回复
热议问题