facebook youtube pinterest twitter reddit whatsapp instagram

Saving Data with NSUserDefaults

In today’s tutorial, I will show you how to save data that will persist through application sessions using NSUserDefaults. This class is a Foundation class that is very useful to save small amounts of data without using a database. However, you cannot save any type of object using this class. You can only use it to save Property Lists.

What is a Property List?

A property list is a structured data representation used by Cocoa and Core Foundation as a convenient way to store, organize, and access standard types of data. They are commonly referred to as plists. Property lists can only contain the following classes:

  • NSArray
  • NSDictionary
  • NSNumber
  • NSData
  • NSString
  • NSDate

An NSArray is a plist only if all the elements in it are property lists too. Also, an NSDictionary is a property list if all of its keys and values are too.

Using NSUserDefaults

NSUserDefaults is used to store property lists, it is like an NSDictionary that persists between launches of the application. It is typically used to save information such as the settings of your app, high scores, etc. If you need to store a large amount of data, then NSUserDefaults is not what you are looking for.

As I said, NSUserDefaults is basically an NSDictionary, so when you save data you also need to save a key to retrieve the value later.

NSUserDefaults *settings = [NSUserDefaults standardUserDefaults]; 
[settings setInteger:myInteger forKey:@"MyIntegerKey"];

Once you have added the objects you want to save to the NSUserDefaults object, you need to write it to disk. To do this, you only need to call the method synchronize.

NSUserDefaults *settings = [NSUserDefaults standardUserDefaults]; 
[settings setInteger:myInteger forKey:@"MyIntegerKey"]; 
[settings synchronize];

To retrieve the saved data at the beginning of your application, you will also need to call the standardUserDefaults function. To get an NSString, for example, this is how the code would look like:

NSUserDefaults *settings = [NSUserDefaults standardUserDefaults]; 
NSString *myString = [defaults objectForKey:@"MyStringKey"];

Conclusion

As you can see, saving data that persists through application launches is very easy. However, you can only use this approach for small amounts of data. If you need to store other kind of data, then you should use Core Data, which I will cover in future tutorials.

Leave a comment if you have any doubts, and thanks for reading this tutorial.