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:
  • NSString
  • NSNumber
  • NSDate
  • NSArray
  • NSDictionary
  • NSData
NSUserDefaults should be used to store small amounts of data.  Here is simple use of NSUserDefaults to save the user name so that the next time they open up the app, I don’t have to ask them again. In this case, it would be overkill for me to store this type of data in Core Data or other complex mechanism. I simply check NSUserDefaults for a value and go from there. It is important to remember that NSUserDefaults are just that, helpful for reading/writing user preferences and other similar things.

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:
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.

1. let refs = NSUserDefaults.standardUserDefaults()
Once we have the reference saved to a constant, we can read data from it.
  1. 1. if let name = refs.stringForKey("userName"){
  2. 2. println("User Name: " + name)
  3. 3. }else{
  4. 4. //Nothing stored in NSUserDefaults yet. Set a value.
  5. 5. prefs.setValue("Json Smith", forKey: "userName")
  6. }
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.
Gopinath TB, 
CEO, Meteora Gaming
www.meteoragaming.com


Other blogs by the author
55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 09 08 07 06 05 04 03 02 01 

Comments

Popular posts from this blog

Internet of Things - MindMap

Creating a Mobile Strategy: Find out the top 10 ways!

How to use Objective C in Swift?