我的应用关闭后保存变量(快速)

问题描述:

我正在尝试在Xcode中保存变量,以便即使在应用程序关闭后也能保存,但是当我访问它时,我从几个不同的类和文件中执行它,并且我在更改变量的值时我访问它。因此类似的线程不完全适用,要存储的值是一个字符串,这是我到目前为止的代码:

I'm trying to save a variable in Xcode so that it saves even after the app has closed, how ever when I access it I do it from a several different classes and files, and I change the value of the variable when I access it. Therefore similar threads do not completely apply, the value to be stored is a string and here is the code I have up until now:

var defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(Token, forKey: "") as! String

我相信这是正确的格式,但我不知道如何调用它来改变因为当我尝试时,我收到一条错误消息,说明预期的声明。

I believe this is the correct format, but I don't know how to call it to change it because when I try I get an error message saying expected declaration.

无论如何,任何帮助都会非常感激。

Anyway any help would be very much appreciated.

首先,您必须指定一个唯一键来存储变量(在示例 MyKey 中)。

First of all you have to specify an unique key to store the variable (in the example MyKey ).

AppDelegate> applicationDidFinishLaunching 使用默认值注册密钥。

好​​处是你可以使用非可选变量,并且你有一个已定义的默认值。

In AppDelegate > applicationDidFinishLaunching register the key with a default value.
The benefit is you can use a non-optional variable and you have a defined default value.

let defaults = UserDefaults.standard
let defaultValue = ["MyKey" : ""]
defaults.register(defaults: defaultValue)

现在你可以从各处读取密钥的价值

Now you can from everywhere read the value for the key

let defaults = UserDefaults.standard
let token = defaults.string(forKey: "MyKey")

并保存

let defaults = UserDefaults.standard
defaults.set(token, forKey: "MyKey")