Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using NSUserDefaults how to save a key before app is first run

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?

like image 973
willc2 Avatar asked Jan 20 '26 10:01

willc2


1 Answers

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.

like image 80
Ole Begemann Avatar answered Jan 22 '26 07:01

Ole Begemann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!