Sunday, 21 October 2012

Use NSUserDefaults to store default values or user settings for an application...

NSUserDefaults is the class which is used to store default values for an application. It stores the values inside the application's sandbox. The values which can be stored are either scalar or which can be serialized into a property list.
NSUserDefaults is a singleton, means it can have only one instance for an application. You don't have to worry about the storage location, updating data or deallocating the object once its use is over. This all is being handled by NSUserDefaults. Infact, NSUserDefaults also caches the information in the memory so that disk read/write is reduced.
NSUserDefaults periodically keeps on synchronizing the values stored in memory with the values stored in disk. It also provides the synchronize method, which can be used to synchronize the values explicitly. It stores objects using key-value pair.
Now, let's see how to use this class for storing defaults.
Get the singleton object  
NSUserDefaults *userdefaults = [NSUserDefaults standardUserDefaults];
  Store/read values
There are some setters and getters methods to store and retrieve values.
[userdefaults setDouble:2.41 forKey:@"doublevalue"]; 
[userdefaults doubleForKey:@"doublevalue"]; 
  Similar type of methods are there for float and integer as well.
 To set an object for a key we can use
NSArray userarray = [[NSArray alloc] init..........];
 [userdefaults setObject:userarray forKey:@"arr"]; 
[userdefaults objectForKey:@"arr"];
  In the above code, we have set an array object.
NSUserDefaults also provides the facility for storing default values in userdefaults. We can store default values for usedefaults until user sets the values. This can be done by using registerDefaults method of NSUserDefaults. This method takes an NSDictionary objects as its parameter.
NSMutableDictionary *defval = [NSMutableDictionary dictionary]; 
[defs setObject:@”Beginner” forKey:@”Level”];
 [[NSUserDefaults standardUserDefaults] registerDefaults:defval];

For more info visit

No comments:

Post a Comment