Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSUserDefaults not present on first run on simulator

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?

like image 976
Ben Collins Avatar asked Dec 18 '22 00:12

Ben Collins


1 Answers

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.

like image 82
user362178 Avatar answered Jan 13 '23 20:01

user362178