Saturday, May 7, 2011

NSUserDefaults

This class helps you to easily save data (mostly preferences) to the iPhone so that you can recover it later.
So if you have an NSString, NSDictionary, NSArray,BOOL, NSDate or NSNumber you can easily use NSUserDefaults to store data.

In the background the system stores all these data types in plists, so NSUserDefaults is also a convenient method to deal with plists.

To do this you would first want to get a reference to the object of this class. This is done by calling this method
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];


This is a shared object so even if you create two references to it, it will ultimately be the same. 


Now let us initialise a few variables so that we may store it for later use.


NSString *name = [NSString stringWithString:@"John"];
NSArray *subjects = [NSArray initWithObjects:@"Physics",@"Maths",@"Management",nil];
NSDate *joinDate = [NSDate date];


We have three variables which we need to store into the system.
This is done by the following code


[userDefaults setObject:name forKey:@"Name"];
[userDefaults setObject:subjects forKey:@"Subjects"];
[userDefaults setObject:joinDate forKey:@"Date"];


Each method call stores one object into memory. 
You can retrieve the saved data through the key so it is important to name it something which is relevant to the data being stored.


Now that we have successfully had a look at the code to store data let us move on to retrieving that data. For that you should have a reference to the NSUserDefaults object. The method objectForKey returns the stored data (in case of BOOL it is boolForKey: ) So let us retrieve the data we stored.

NSString *savedName = [userDefaults objectForKey:@"Name"];
NSArray *savedSubjects = [userDefaults objectForKey:@"Subjects"];
NSDate *savedDate = [userDefaults objectForKey:@"Date"];


All of the above discussion was for objects, but there are a few data types like integers and floats which aren't objects but you might need to store them. The SDK has specific methods for each of them, here they are:

setInteger:forKey:,integerForKey: 
setBool:forKey,boolForKey: 
setFloat:forKey,floatForKey: 
setDouble:forKey,DoubleForKey: 

Even now one important question hasn't been answered yet, which is, when to save and retrieve this data?


If this data is required at the start of the application itself this it would be a good idea to retrieve saved data in the applicationDidFinishLaunching method.

You would want to save data when the home button is pressed, i.e your application is going to get closed or put into the background (iOS 4 and later). So the code for saving data should be put in applicationWillTerminate: and applicationWillResignActive:

With this you should be able to effectively save state of your application and save user data.









No comments: