Save variable after my app closes (swift)

孤街醉人 提交于 2019-12-20 09:45:53

问题


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.


回答1:


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

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")

and save it

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



回答2:


Swift 3

(thanks to vadian's answer)

In AppDelegate > applicationDidFinishLaunching :

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

to save a key:

let defaults = UserDefaults.standard
defaults.set("someVariableOrString", forKey: "myKey")
defaults.synchronize()

to read a key:

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



回答3:


Let's say you have a string variable called token

To save/update the stored value on the device:

NSUserDefaults.standardUserDefaults().setObject(token, forKey: "mytoken")
NSUserDefaults.standardUserDefaults().synchronize()

In the code above I made sure to give the key a value ("mytoken"). This is so that we later can find it.

To read the stored value from the device:

let token = NSUserDefaults.standardUserDefaults().objectForKey("mytoken") as? String

Since the method objectForKey returns an optional AnyObject, I'll make sure to cast it to an optional String (optional meaning that it's either nil or has a value).




回答4:


Add default.synchronize() after setting value.



来源:https://stackoverflow.com/questions/31923410/save-variable-after-my-app-closes-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!