0

I am making sounds enabled UserDefaults, I am managing then good and it works then I set YES/NO values.

    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:kSoundEnabled];
    [[NSUserDefaults standardUserDefaults]synchronize];

How to set YES sound parameter for first app run and where can I do it?

Wain
  • 118,658
  • 15
  • 128
  • 151
user3358463
  • 125
  • 15
  • 2
    why not just check [[NSUserDefaults standardUserDefaults] objectForKey:kSoundEnabled] == nil and set your local variable to YES? – Owen Hartnett Mar 12 '14 at 16:08

2 Answers2

8

You can set initial values using registerDefaults: which takes an NSDictionary of all your initial keys and their respective values. Example:

[[NSUserDefaults standardUserDefaults] registerDefaults:@{ kSoundEnabled : @YES }];
JustSid
  • 25,168
  • 7
  • 79
  • 97
  • 3
    ... which is implemented in a nice way: registered defaults aren't stored to disk, just checked in memory if nothing is stored. So you can change those defaults freely whenever you want with no legacy issues. – Tommy Mar 12 '14 at 16:11
0

In your application delegate (usually AppDelegate.m ) do

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
   NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
   if([userDefaults objectForKey:kSoundEnabled] == nil) {
      [userDefaults setObject:@YES forKey:kSoundEnabled];
      [userDefaults synchronize];
   }
}
XeNoN
  • 694
  • 6
  • 16
  • It MUCH better to use `NSUserDefaults registerDefaults:`. – rmaddy Mar 12 '14 at 16:26
  • @rmaddy, why do you think so? – user3358463 Mar 12 '14 at 16:37
  • @user3358463 Because that is its purpose. It is there to setup default values without the need to check for `nil` or to write initial values. Once the defaults are registered, you don't need any special logic in any of your code to check to see if there is a value or not for a given key. You simply get a value and act accordingly. It's much cleaner. – rmaddy Mar 12 '14 at 17:13
  • @rmaddy, aha, I read that code in that answer is better then registerDefaults, all right ,) – user3358463 Mar 12 '14 at 17:39
  • @user3358463 No, I was telling XeNoN that it is better to use `registerDefaults:` than the code in their answer. – rmaddy Mar 12 '14 at 17:49