Wednesday, June 15, 2011

NSUserDefaults Example Code

NSUserDefaults is generally used for storing information of an app with in application's sandbox. It comes very handy when you want to store very small amount of information. Like if you have a login screen and you want to store the username and password for next login for user's convenience, then its best to use NSUserDefaults ! I am going to tell you how you can do it.

First you need to create an instance of NSUserDefault in your code

NSUserDefaults *userDefaults=[NSUserDefaults standardUserDefaults];

Then you can save data of various kinds as shown following:

This lets you save an integer as NSNumber for key IndexForZ

[userDefaults setObject:[NSNumber numberWithInt:myInteger] forKey:@"IndexForZ"];

You can save a string as following

[userDefaults setObject:@"Reetu" forKey:@"name"];

Following methods let you save as they: Integer, float, double, bool and url respectively !

- (void)setInteger:(NSInteger)value forKey:(NSString *)defaultName;

This could be used as:

[userDefaults setInteger:1 forKey:@"rank"];

Other methods available in the iOS SDK are:

- (void)setFloat:(float)value forKey:(NSString *)defaultName;
- (void)setDouble:(double)value forKey:(NSString *)defaultName;
- (void)setBool:(BOOL)value forKey:(NSString *)defaultName;
- (void)setURL:(NSURL *)url forKey:(NSString *)defaultName;

To retrieve the values from these keys in NSUserDefaults anywhere in your application , on any view controller... you can just again create an instance of NSUserDefaults and use stringForKey or integerForKey

NSUserDefaults *userDefaults=[NSUserDefaults standardUserDefaults];
NSString *nameVal=[userDefaults stringForKey:@"name"];
NSInteger rank =[userDefaults integerForKey:@"rank"];

No comments:

Post a Comment