view raw
Jay Jay - 6 months ago 35
Swift Question

How do I set and load NSUserDefaults in AppDelegate

In didFinishLaunchingWithOptions I have:

let defaults = NSUserDefaults.standardUserDefaults()
if let name = defaults.stringForKey("userNameKey") {

In the applicationWillTerminate I have:

let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject("Coding Explorer", forKey: "userNameKey")

But upon application load(which i've closed and reopened several times on the iphone simulator), it does not print. Any clue why?


it could be better to use debugger to see whether or not your code invoke the following method applicationWillTerminate

Before we read or write data from NSUserDefaults, we must first get a reference to the NSUserDefaults class.

let prefs = NSUserDefaults.standardUserDefaults()

For further information:

Once we have the reference saved to a constant, we can write data to it. You will be defining both the value and the key name to store the data.

prefs.setValue("Berlin", forKey: "userCity")

//This code saves the value "Berlin" to a key named "userCity".

More information could be found in the following link: