3

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?

willc2
  • 38,991
  • 25
  • 88
  • 99
  • code example here http://stackoverflow.com/questions/1664177/best-way-to-check-if-an-iphone-app-is-running-for-the-first-time/1664284#1664284 – brian.clear Mar 20 '12 at 11:23

2 Answers2

6

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
  • 135,006
  • 31
  • 278
  • 256
2

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
  • 52,708
  • 13
  • 106
  • 123