NSUserDeafaults / Saving User SettingsDecember 02, 2010 08:32 am Posted By: bytedissident
It’s a very common practice to save/persist settings, preferences and login credentials in our applications. Apple has made this task very easy for us via the NSUserDefaults object. Below is a quick step by step of how to use it.
Step 1:
Instantiate NSUserDefaults:
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
Step 2:
Set a default in the following manner, this just your typical objecting setting for a key value pair (dictionary).
[prefs setObject:@"my value" forKey:@"my_setting"];
Synchronize your settings
[prefs synchronize];
Step 3:
Read the preference back later.
[prefs stringForKey:@"my_setting"];
NOTE:
The one thing to pay attention to here is the data type. In this case I am asking for a string, but you may use other data types check out the methods below
- (NSString *)stringForKey:(NSString *)defaultName;
- (NSArray *)arrayForKey:(NSString *)defaultName;
- (NSDictionary *)dictionaryForKey:(NSString *)defaultName;
- (NSData *)dataForKey:(NSString *)defaultName;
- (NSArray *)stringArrayForKey:(NSString *)defaultName;
- (NSInteger)integerForKey:(NSString *)defaultName;
- (float)floatForKey:(NSString *)defaultName;
- (double)doubleForKey:(NSString *)defaultName;
- (BOOL)boolForKey:(NSString *)defaultName;
- (NSURL *)URLForKey:(NSString *)defaultName
Now once you set your NSUserDefault it will be saved to your app and persist between launches.
Download Code
|