views:

221

answers:

2

I have an app where I need a BOOL value to persist across launches.

The value should be YES on the first launch and user-customizable thereafter.

But if it's the first launch, how do I set the default to YES before the program is run?

+5  A: 

You need to register a dictionary of default values with NSUserDefaults on every launch of your app:

NSDictionary *defaultValues = [NSDictionary dictionaryWithObject:
    [NSNumber numberWithBool:YES] forKey:@"myUserDefaultsKey"];
[[NSUserDefaults standardUserDefaults] registerDefaults:defaultValues];

Now,

[[NSUserDefaults standardUserDefaults] boolForKey:@"myUserDefaultsKey"];

will return YES if the key is not present.

Ole Begemann
+1  A: 

One solution is to include a plist file with the default values in your app. If the preferences are not available (first launch), then simply creates them from the default plist file...

Macmade