let defaults = NSUserDefaults.standardUserDefaults()
defaults.setInteger(25, forKey: "Age")
defaults.setBool(true, forKey: "UseTouchID")
defaults.setDouble(M_PI, forKey: "Pi")
defaults.setObject("Paul Hudson", forKey: "Name")
defaults.setObject(NSDate(), forKey: "LastRun")
When you set values like that, they become permanent – you can quit the app then re-launch and they'll still be there, so it's the ideal way to store app configuration data.
As mentioned, you can use
NSUserDefaults
to store arrays and dictionaries, like this:let array = ["Hello", "World"]
defaults.setObject(array, forKey: "SavedArray")
let dict = ["Name": "Paul", "Country": "UK"]
defaults.setObject(dict, forKey: "SavedDict")
When it comes to reading data back, it's still easy but has an important proviso:
NSUserDefaults
will return a default value if the setting can't be found. You need to know what these default values are so that you don't confuse them with real values that you set. Here they are:integerForKey()
returns an integer if the key existed, or 0 if not.boolForKey()
returns a boolean if the key existed, or false if not.floatForKey()
returns a float if the key existed, or 0.0 if not.doubleForKey()
returns a double if the key existed, or 0.0 if not.objectForKey()
returns AnyObject? so you need to conditionally typecast it to your data type.
With that in mind, you can read values back like this:
let defaults = NSUserDefaults.standardUserDefaults()
let age = defaults.integerForKey("Age")
let useTouchID = defaults.boolForKey("UseTouchID")
let pi = defaults.doubleForKey("Pi")
When retrieving objects, the result is optional. This means you can either accept the optionality, or typecast it to a non-optional type and use the nil coalescing operator to handle missing values. For example:
let array = defaults.objectForKey("SavedArray") as? [String] ?? [String]()
沒有留言:
張貼留言