Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone App : How to get default value from root.plist?

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

like image 338
Harish J Avatar asked Sep 16 '09 05:09

Harish J


2 Answers

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.

like image 72
Mike Weller Avatar answered Oct 13 '22 19:10

Mike Weller


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");
like image 4
mahboudz Avatar answered Oct 13 '22 18:10

mahboudz