Initialize IOS Preferences from Preference Bundle

2019-09-09 02:00发布

问题:

In my AppDelegate.m I'm trying to initialize the default values from my Preference Bundle if the user hasn't gone to the settings pane yet. The initialize runs, and I see the correct number of objects for my preferences but they're all null and nothing gets set.

+ (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:

You are registering an empty dictionary.

Use :

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