如何在swift上使用sharedInstance作为全局变量?

时间:2014-12-24 02:52:29

标签: ios swift storyboard segue viewcontroller

是否可以识别在一个类,另一个类或视图控制器中定义的共享实例值,或者甚至在另一个函数中?

如何在这里获得单例变量:

        self.user.userId = 42
        self.user.name = too as String
        println(self.user.name) // 42

要传递并在其中作为相同的变量引用(例如,self.user.userId仍会打印42?

override func prepareForSegue(segue: (UIStoryboardSegue!), sender: AnyObject!) {
    if (segue.identifier == "segueTest") {
        var svc = segue!.destinationViewController as secondViewController;
        svc.toPass = self.user.name as String
        println("he")
        println(self.user.userId)
        println(svc.toPass)}
}}

xcode 6.1.1 sharedinstance

我在.swift文件中有这个:

class User {
    class var sharedInstance: User {
        struct Static {
            static var instance: User?
            static var token: dispatch_once_t = 0
        }

        dispatch_once(&Static.token) {
            Static.instance = User()
        }

        return Static.instance!
    }

    var userId: Int = 0
    var name: String = ""
}

1 个答案:

答案 0 :(得分:0)

如果不是很多数据,我用来在视图控制器之间传递数据的策略是将值存储在NSUserDefaults中。

设置值:首次获取数据时,请将其存储在NSUserDefaults

let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults() //This class variable needs to be defined every class where you set or fetch values from NSUserDefaults
defaults.setValue(42, forKey: "userID")
defaults.setValue("too", forKey: "username")
defaults.synchronize() //Call this when you're done editing the defaults. It saves your changes to the disk

获取值:当您需要获取值时,只需从NSUserDefaults抓取它。

let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
let userID = defaults.objectForKey("userID") as? Int
let username = defaults.objectForKey("username") as? String

这样做可以让您访问任何类中的存储值,并允许数据在应用关闭并重新打开后保持不变。如果您想在应用关闭后清除数据,请在AppDelegate applicationWillTerminate(application: UIApplication)函数中为以前设置的每个键调用removeObjectForKey函数。

let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
defaults.removeObjectForKey("userID")
defaults.removeObjectForKey("username")
defaults.synchronize()

有关NSUserDefaults的有用资料

NSUserDefulats课程参考:链接here