NSUserDefaults - Swift
NSUserDefaults is a class that allows simple storage of different data types. It is ideal for small bits of information you need to persist between app launches or device restarts.
NSUserDefaults supports the following data types:
NSUserDefaults supports the following data types:
- NSString
- NSNumber
- NSDate
- NSArray
- NSDictionary
- NSData
Saving data:
Before we read or write data from NSUserDefaults, we must first get a reference to the NSUserDefaults class.
1. let refs = NSUserDefaults.standardUserDefaults()
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.
1. refs.setValue("Json Smith", forKey: "userName")
//This code saves the value "Json Smith" to a key named "userName".
Reading data is similiar to writing it. Again, let’s get a reference to the NSUserDefaults class and then we can query a key for a value.//This code saves the value "Json Smith" to a key named "userName".
Reading data:
1. let refs = NSUserDefaults.standardUserDefaults()
Once we have the reference saved to a constant, we can read data from it.
- 1. if let name = refs.stringForKey("userName"){
- 2. println("User Name: " + name)
- 3. }else{
- 4. //Nothing stored in NSUserDefaults yet. Set a value.
- 5. prefs.setValue("Json Smith", forKey: "userName")
- }
We are querying (in this case) the key named “userName” for a value. If the key returns a value, we print it out to the console. Otherwise, if there is no value saved yet, we use .setValue to save the name to NSUserDefaults.
In this case we are saving a string but you can use this with any of the data types described above. If you need to persist when the app was last opened, you can use NSDate in combination with NSUserDefaults.
Comments