Pages

July 4, 2013

Save default settings (Bundle -> Root.plist)

The default settings you store in Settings bundle file will not be applied on the first setup of the app. I don't know why, maybe it's a bug.
You can go beyond this limitation simply executing this code on your fist app launch.


/** Register default settings stored in Settings.bundle -> Root.plist.

 These settings are not automatically applied on first installation of the app, so you have to call this function.

 @return Returns true on success, false otherwise.

 */
+ (BOOL)registerDefaultsFromSettingBundle {
    NSString *settingsBundle = [[NSBundle mainBundle] pathForResource:@"Settings" ofType:@"bundle"];
    if (!settingsBundle) {
        return NO;
    }

    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];
    return YES;
}



Download the ready-for-use source file (.m) of Save default settings (Bundle -> Root.plist)

No comments:

Post a Comment