Thursday, September 22, 2016

Singleton Class in Swift (Global shared data)



First we have to create the empty file.

Xcode -> New -> File -> Others -> Empty file


//  GlobalData.swift

class GlobalData {
    
    var defaultLocationID : String = "0"
    var userEmailsave :String = ""
    var userLocationAdress : String = ""
    var userLocationArray : NSMutableArray!
    var userLocationSelected : String = ""
    var tokenAPI : NSString = ""
    var default_location_name : String = ""
    var userName : String = ""
    
    // Here is how you would get to it without there being a global collision of variables.
    // , or in other words, it is a globally accessable parameter that is specific to the
    // class.
    class var sharedManager: GlobalData {
        struct Static {
            static let instance = GlobalData()
        }
        return Static.instance
    }

}


//   HomeViewController.Swift

 GlobalData.sharedManager.userName = "Facebook Username or google username"

we can access the global data like this.

No comments:

Post a Comment