Monday 18 August 2014

NSUserDefaults iPhone/Objective c

iPhone Tutorial – Saving/Retrieving Data Using NSUserDefaults :

The NSUserDefaults class provides a programmatic interface for interacting with the defaults system. The defaults system allows an application to customize its behavior to match a user’s preferences.

At runtime, you use an NSUserDefaults object to read the defaults that your application uses from a user’s defaults database. NSUserDefaults caches the information to avoid having to open the user’s defaults database each time you need a default value. The synchronize method, which is automatically invoked at periodic intervals, keeps the in-memory cache in sync with a user’s defaults database.

Saving to NSUserDefaults :
========================

Basically, all you have to do is load NSUserDefaults, and then tell it to save a value to a specific key. Here is a simple example of writing an integer to NSUserDefaults:

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; [defaults setInteger:101 forKey:@"RollNo"]; 
[defaults synchronize];

As mentioned earlier,
we loaded the NSUserDefaults plist to the object “defaults”. We then told that object to set an integer for the key “RollNo”.
But we know that, we must have to use “synchronize” method to save the value. It isn’t absolutely necessary, because this is called automatically every so often, but if you want to be sure to save the changes to NSUserDefaults right now, this is how.


Other Samples for NSUserDefaults :
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];     

// saving an NSString
[prefs setObject:@"IT0809" forKey:@"AccessNo"];
   
// saving an NSInteger
[prefs setInteger:42 forKey:@"RollNo"];
    

// saving a Double
[prefs setDouble:9.99 forKey:@"DoubleKey"];
    

// saving a Float
[prefs setFloat:1.7565671 forKey:@"FloatKey"];
    

[prefs synchronize];

Reading from NSUserDefaults
========================

Reading is even easier, as shown below:

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSInteger theHighScore = [defaults integerForKey:@"
RollNo"];
 
 
Other Samples for NSUserDefaults :
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

// getting an NSString

NSString *myString = [prefs stringForKey:@"AccessNo"];

// getting an NSInteger

NSInteger myInt = [prefs integerForKey:@"RollNo"];

// getting an Float

float myFloat = [prefs floatForKey:@"FloatKey"];

Delete all keys from a NSUserDefaults dictionary iPhone :

- (void)resetDefaults {
     NSUserDefaults * defs = [NSUserDefaults standardUserDefaults];
     NSDictionary * dict = [defs dictionaryRepresentation];
     for (id key in dict) {
           [defs removeObjectForKey:key];
     }
     [defs synchronize];
}


Refer this Links :

  1. http://www.icodeblog.com/2008/10/03/iphone-programming-tutorial-savingretrieving-data-using-nsuserdefaults/
  2. http://ios-blog.co.uk/tutorials/quick-tips/storing-data-with-nsuserdefaults/