将数据存储在Swift中

时间:2014-11-19 10:06:17

标签: swift xcode6

我对与Swift相关的编程有一个一般性的问题。例如,当我想在我的应用程序中存储Int值时,因为我在整个应用程序中使用此变量。所以我有三个选择:

//FIRST
//In my AppDelegate I do this
var myInt = 3
//And later I can use this when I do
let delegate = UIApplication.sharedApplication().delegate as AppDelegate
delegate.myInt = 5

//SECOND
//I can store the value in UserDefaults
NSUserDefaults.standardUserDefaults().setInteger(myInt, forKey: "myInt")
NSUserDefaults.standardUserDefaults().synchronize()
//and later get them by
var anotherInt = NSUserDefaults.standardUserDefaults().integerForKey("myInt")

//THIRD
//I can define a structure as my Data storage
struct myData {
    static var myInt = 3
}
//and later get the value by
myData.myInt = 5

所以我的问题是,我应该使用哪一个?或者不应该存储任何全球价值观? 很想听听你的消息:]

1 个答案:

答案 0 :(得分:1)

如果希望变量在应用启动之间保持不变,则选项1可以正常工作。

如果执行希望变量在应用启动之间保持不变,则选项2可以正常工作。

选项3也可以有效但不持久。

我会说选项1或2是更常用的,具体取决于你是否需要变量持久化。

相关问题