Posted by: bearc0025 | April 14, 2009

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:


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

About these ads

Responses

  1. [...] worries, though. This gap in expectations has been well discussed on teh intertubes. In addition, Apple does provide a reference implementation in the AppPrefs project. However, the [...]


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

Follow

Get every new post delivered to your Inbox.

Join 388 other followers

%d bloggers like this: