Using NSUserDefaults in iOS

Hi All,

I know that most of the people reading the post are familiar with the concept of NSUserDefaults.

Just to summarize, NSUserDefaults is a programmatic interface to interact with the user system. It allows the application to store and access the data that is specific to the user.  So lets just quickly see how to access and store the data specific to the user in the iOS application context.

The data stored in the NSUserDefaults is persistent data and exists in the device even after the application has been terminated. As said we should use the space judiciously i.e. we should not over use the space available and only use it when we have to save something which should be available even after the application has been shutdown.

Adding Objects

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

[defaults setObject:object_name forKey:@"key_name"];

[defaults synchronize];

The above statements adds/store an object to the application user defaults context. We can add the values but these values are not actually stored to the context till we call synchronize message on the defaults object i.e. [defaults synchronize]. Whenever we are making a change to the context we must call the synchronize to update the changes in the context.

Retreive Data

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

id Object = [defaults objectForKey:@"KeyName"];

We can store any type of objects in the user defaults space.

Storing Custom Arrays

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:[NSKeyedArchiver archivedDataWithRootObject:objectName] forKey:@"keyname"];
[defaults synchronize];

The above piece of code allows the user to store the custom array of objects in the NSUserDefaults.

Retrieving Data

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *data = defaults objectForKey:@"keyname"];
NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithData:data];

Removing all objects

We can even erase all the application specific data from the NSUserDefaults. This is how we do it.

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSDictionary *dicitionary = [defaults dictionaryRepresentation];
for(id key in dicitionary)
{
[defaults removeObjectForKey:key];
}
[defaults synchronize];

I hope you enjoyed the post. In case there is anything you wanna communicate please do let me know.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s