iPhone - reading Setting.bundle returns wrong values

Duck picture Duck · Mar 30, 2011 · Viewed 7.3k times · Source

I have created a Settings.bundle that came with a Root.plist file and a localization directory en.lproj.

I have edited Root.plist and added several settings I want to have for my app.

When I delete the app from iPhone and install it and run the first time, all settings I read return wrong values. For example:

highQualityFlag = [[[NSUserDefaults standardUserDefaults] stringForKey:@"qualityFlag"] boolValue];

the flag comes as NO, even if the setting default is YES.

If I change something on the settings and run again, all subsequent runs give me the correct values (??)

How do I solve that?

thanks

Answer

0x8badf00d picture 0x8badf00d · Mar 30, 2011

Try this:

- (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];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{    
    [self registerDefaultsFromSettingsBundle];

    window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
        [window makeKeyAndVisible];
    return YES;
}