I am working on an iPhone app
I read a key from root.plist like this :
NSString *Key1Var = [[NSUserDefaults standardUserDefaults] stringForKey:@"Key1"];
("Key1" is a PSMultiValueSpecifier
for which a default string value has been set already in root.plist)
That works fine, once the user makes settings.
But if the user runs the app before he does any setting, he will get nil
for "Key1".
In such case, I was expecting the default value that i had set for "Key1".
what i need to do,
so that the user does not have to do setting, to make application run for the first time?
Regards, Harish
See this question for a complete solution.
You essentially want to run this code before accessing the setting:
- (void)registerDefaultsFromSettingsBundle {
NSString *settingsBundle = [[NSBundle mainBundle] pathForResource:@"Settings" ofType:@"bundle"];
if(!settingsBundle) {
NSLog(@"Could not find Settings.bundle");
return;
}
NSDictionary *settings = [NSDictionary dictionaryWithContentsOfFile:[settingsBundle stringByAppendingPathComponent:@"Root.plist"]];
NSArray *preferences = [settings objectForKey:@"PreferenceSpecifiers"];
NSMutableDictionary *defaultsToRegister = [[NSMutableDictionary alloc] initWithCapacity:[preferences count]];
for(NSDictionary *prefSpecification in preferences) {
NSString *key = [prefSpecification objectForKey:@"Key"];
if(key) {
[defaultsToRegister setObject:[prefSpecification objectForKey:@"DefaultValue"] forKey:key];
}
}
[[NSUserDefaults standardUserDefaults] registerDefaults:defaultsToRegister];
[defaultsToRegister release];
}
This will load the default values into the standardUserDefaults
object so you will no longer get back nil values, and you don't have to duplicate the default settings in your code.
I do this early after launch, before I try to get my settings:
userDefaultsValuesPath=[[NSBundle mainBundle] pathForResource:@"UserDefaults"
ofType:@"plist"];
userDefaultsValuesDict=[NSDictionary dictionaryWithContentsOfFile:userDefaultsValuesPath];
// set them in the standard user defaults
[[NSUserDefaults standardUserDefaults] registerDefaults:userDefaultsValuesDict];
if (![[NSUserDefaults standardUserDefaults] synchronize])
NSLog(@"not successful in writing the default prefs");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With