iPhone Default User Settings Null?

I wanted to set default values for my application using a Settings.bundle and I ran into an interesting issue with iPhone SDK 2.2. If you don't run the Settings application before your application runs for the first time, then the default settings are not set. It turns out that you'll need to manually set them on the first time the application is run.

Setting defaults to the default value...

I'm not sure why there isn't a function that can set the values for me, but after digging I found someone who ran into the same dilema. I don't want to have multiple locations with default values (code and a Settings.bundle), so I found a programmatic way to set all the default values if they haven't been set.

- (void)registerDefaultsFromSettingsBundle {
    NSString *settingsBundle = [[NSBundle mainBundle] pathForResource:@"Settings" ofType:@"bundle"];
    if(!settingsBundle) {
        NSLog(@"Could not find Settings.bundle");

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

All you have to do is call the above function if one of your Standard User Defaults returns null. Make the call once your application finishes loading like so:

- (void)applicationDidFinishLaunching:(UIApplication *)application {
	// Get the application user default values
	NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
	NSString *server = [user stringForKey:@"server_address"];
	if(!server) {
		// If the default value doesn't exist then we need to manually set them.
		[self registerDefaultsFromSettingsBundle];
		server = [[NSUserDefaults standardUserDefaults] stringForKey:@"server_address"];
    [window addSubview:viewController.view];
    [window makeKeyAndVisible];


[ad#Large Box]