views:

292

answers:

3

I've got some settings saved in my Settings.bundle, and I try to use them in application:didFinishLaunchingWithOptions, but on a first run on the simulator accessing objects by key always returns nil (or 0 in the case of ints). Once I go to the settings screen and then exit, they work fine for every run thereafter.

What's going on? Isn't the point of using default values in the Settings.bundle to be able to use them without requiring the user to enter them first?

+2  A: 

Isn't the point of using default values in the Settings.bundle to be able to use them without requiring the user to enter them first?

No. The point of the settings bundle is to give the user a place to edit all 3rd Party app settings in a convenient place. Whether or not this centralization is really a good idea is a User Experience issue that is off topic.

To answer your question, you should detect if it is the first load, then store all your defaults initially.

And while we are on the subject, I would also check out In App Settings Kit as it provides your app with a simple way to display your app settings in both places (in-app and Settings.app) with minimal code.

coneybeare
How do I do that? The only way I can tell from the documentation that objects get written to the defaults store is by calling `synchronize`. I tried that, but it didn't work (presumably because there aren't any changes in the in-memory settings to write to the store).
Ben Collins
you have to explicitly set the default value for a key (the same key in settings.bundle), then synchronize
coneybeare
A: 

Hi Ben,

As coneybeare said "You should detect if it is the first load, then store all your defaults initially."

On applicationDidFinishLaunching try to set default value in your preference.

Here is the sample:

NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
if([defaults objectForKey:@"YOUR_KEY"] == nil)
{
    [defaults setValue:@"KEY_VALUE" forKey:@"YOUR_KEY"];
}

When application will run second time it will come with KEY_VALUE for YOUR_KEY.

Thanks,
Jim.

Jim
+1  A: 

If I got your question right, in your app delegate's - (void)applicationDidFinishLaunching:(UIApplication *)application, set the default values for your settings by calling registerDefaults:dictionaryWithYourDefaultValues on [NSUserDefaults standardUserDefaults]

- (void)applicationDidFinishLaunching:(UIApplication *)application {    
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          [NSNumber numberWithInt:3], @"SomeSettingKey",
                          @"Some string value", @"SomeOtherSettingKey",
                          nil];
    [ud registerDefaults:dict];
}

These values will only by used if those settings haven't been set or changed by previous executions of your application.