Wednesday, July 22, 2015

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

6 comments:

  1. Very simple and easy to understand. Thank you very much for sharing the info !

    ReplyDelete
  2. was searching for NSUserDefaults and came across this blog. Can you also please add the uses of NSUserDefaults or where it can be used?
    overall - well written article!

    ReplyDelete