我的应用关闭后保存变量(快速) [英] Save variable after my app closes (swift)

查看:137
本文介绍了我的应用关闭后保存变量(快速)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在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")

这篇关于我的应用关闭后保存变量(快速)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆