在第一次App加载时从Preference Bundle初始化IOS首选项

时间:2014-04-30 04:38:48

标签: ios nsuserdefaults

在我的AppDelegate.m中,如果用户尚未进入设置窗格,我正在尝试初始化我的Preference Bundle中的默认值。初始化运行,我看到我的首选项的对象数量正确但它们都是null并且没有设置任何内容。

+ (void)initialize {
    NSLog(@"Running settings initialization");
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *settingsBundle =
    [[NSBundle mainBundle] pathForResource:@"Settings" ofType:@"bundle"];
    NSDictionary *settings =
    [NSDictionary dictionaryWithContentsOfFile:
     [settingsBundle stringByAppendingPathComponent:@"Root.plist"]];

    NSArray *preferences = [settings objectForKey:@"PreferenceSpecifiers"];
    NSMutableDictionary *defaultsToRegister =
    [[NSMutableDictionary alloc] initWithCapacity:[preferences count]];

    [defaults registerDefaults:defaultsToRegister];
    [defaults synchronize];

}

1 个答案:

答案 0 :(得分:2)

您正在注册一个空字典。

使用:

+ (void)initialize
{
     NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
     [defs synchronize];

     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)
        {
           // Check if value is registered or not in userDefaults
           id currentObject = [defs objectForKey:key];
           if (currentObject == nil)
           {
              // Not registered: set value from Settings.bundle
              id objectToSet = [prefSpecification objectForKey:@"DefaultValue"];
              [defaultsToRegister setObject:objectToSet forKey:key];
              NSLog(@"Setting object %@ for key %@", objectToSet, key);
           }
           else
           {
              // Already registered
              NSLog(@"Key %@ is already registered with Value: %@).", key, currentObject);
           }
       }
   }

   [defs registerDefaults:defaultsToRegister];
   [defaultsToRegister release];
   [defs synchronize];
}