8

我创建了一个带有 Root.plist 文件和本地化目录 en.lproj 的 Settings.bundle。

我已经编辑了 Root.plist 并添加了一些我想为我的应用程序设置的设置。

当我从 iPhone 中删除应用程序并安装它并第一次运行时,我读取的所有设置都返回错误值。例如:

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

即使设置默认值为“是”,该标志也显示为“否”。

如果我更改设置并再次运行,所有后续运行都会给我正确的值 (??)

我该如何解决?

谢谢

4

1 回答 1

24

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;
}
于 2011-03-30T20:17:59.287 回答