Skip to content

NSUserDefaults/Settings.bundle not loaded, returning nils

Apparently there is a bug/feature in the Apple SDK such that until the user goes into the settings area for an app, the settings are loaded. So you get nils back when checking on values. It kinda defeats the purpose of the DefaultValue setting, but here’s a good work around:

Updating NSUserDefaults from Settings.bundle | greg haygood

I modified the code slightly to run thru all of the settings and if it finds a ‘File’ setting, it runs thru that also recursively. So you just call the  setSettingsBundleDefaults in your app delegate applicationDidFinishLaunching method. I first check to see if a “test” value is there – this value sd be there. If it’s not, I need to run thru my settings:

[sourcecode language=’cpp’]

if (nil == [[NSUserDefaults standardUserDefaults] valueForKey:@”xyz”])
[MyAppDelegate setSettingsBundleDefaults];
+ (void)setSettingsBundleDefaults
{
[MyAppDelegate setSettingsBundleDefaultsForFile:@”Root.plist”];
}
+ (void)setSettingsBundleDefaultsForFile:(NSString*)plistFileName
{
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];

//bundle path
NSString *bPath = [[NSBundle mainBundle] bundlePath];
NSString *settingsPath = [bPath stringByAppendingPathComponent:@”Settings.bundle”];
NSString *plistFile = [settingsPath stringByAppendingPathComponent:plistFileName];

//preferences
NSDictionary *settingsDictionary = [NSDictionary dictionaryWithContentsOfFile:plistFile];
NSArray *preferencesArray = [settingsDictionary objectForKey:@”PreferenceSpecifiers”];

//loop thru prefs
NSDictionary *item;
for(item in preferencesArray)
{
//get the key
NSString *keyValue = [item objectForKey:@”Key”];

//get the default
id defaultValue = [item objectForKey:@”DefaultValue”];

// if we have both, set in defaults
if (keyValue && defaultValue)
[standardUserDefaults setObject:defaultValue forKey:keyValue];

//get the file item if any – (recurse thru the other settings files)
NSString *fileValue = [item objectForKey:@”File”];
if (fileValue)
[MyAppDelegate setSettingsBundleDefaultsForFile:[fileValue stringByAppendingString:@”.plist”]];

}
[standardUserDefaults synchronize];
}

[/sourcecode]

1 thought on “NSUserDefaults/Settings.bundle not loaded, returning nils”

  1. Pingback: Keeping User Defaults Synchronized with Settings.bundle «

Comments are closed.