简体   繁体   中英

Save variable in swift even when app is turned off

Do you guys know how to save a var in swift, even when the app is closed.

When someone opens the app on his phone for the first time he can choose a name, what I want is, if he selected a name at the first time. He don't need to choose anymore and the name is saved even when the app is closed and turned on again.

Thanks!

Best way is to use NSUserDefaults . With the NSUserDefaults class, you can save settings and properties related to application or user data.

ex:

let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject("Foo", forKey: "name")

and then to read

if let name = defaults.stringForKey("name")
{
    println(name)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM