-2

I have to following NSUserDefaults which I wish to be set to yes on the first time the user launches the app? How would I go about doing this? I'm aware it needs to be placed into AppDelegate however I can't work out how to do this.

NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];

[self.truthonoff setOn:[[defaults objectForKey:@"truthonoff"] boolValue] animated:YES];

[self.truthonoff addTarget:self action:@selector(stateSwitched:) forControlEvents:UIControlEventValueChanged];

[self.dareonoff setOn:[[defaults objectForKey:@"dareonoff"] boolValue] animated:YES];

[self.dareonoff addTarget:self action:@selector(stateSwitcheddare:) forControlEvents:UIControlEventValueChanged];
//other options

[self.shakesonoff setOn:[[defaults objectForKey:@"shakesonoff"] boolValue] animated:YES];

[self.shakesonoff addTarget:self action:@selector(stateSwitchedshakes:) forControlEvents:UIControlEventValueChanged];

[self.soundonoff setOn:[[defaults objectForKey:@"soundonoff"] boolValue] animated:YES];

[self.soundonoff addTarget:self action:@selector(stateSwitchedsound:) forControlEvents:UIControlEventValueChanged];
Yuri Solodkin
  • 530
  • 8
  • 26
user3502233
  • 25
  • 1
  • 7
  • possible duplicate of [Detecting the initial launch of an app using NSUserDefaults](http://stackoverflow.com/questions/7023538/detecting-the-initial-launch-of-an-app-using-nsuserdefaults) – BytesGuy Apr 13 '14 at 09:53

3 Answers3

3

What you are looking for is -[NSUserDefaults registerDefaults:]

For example you could do something like:

+ (void)initialize
{
    if ([self class] == [AppDelegate class])
    {
        [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"dareonoff":@NO}];
    }
}

The benefits of using registerDefaults is that deleting the a preference using -[NSUserDefault objectForKey:] reverts the key to it's default value declared in registeredDefaults.

Alej
  • 126
  • 5
0

objectForKey: returns nil when the app is launced for the first time - or to be more accureate, when no value for the key was wever set before.

You should always check for nil when retreiving values from the user defaults. And when it is nil then you go forward with a resonalbe default value.

What happens here is that objectForKey retuns nil. Then you send boolValue to nil which returns a null value whihc is FALSE or NO in case of a bool.

Hermann Klecker
  • 14,039
  • 5
  • 48
  • 71
0

You can add initial values to Root.plist in Settings.bundle. And then you can register these defaults as described in this question:

iPhone - reading Setting.bundle returns wrong values

Community
  • 1
  • 1
Yuri Solodkin
  • 530
  • 8
  • 26