6

I have been looking for an answer but not really found what i am looking for.

I have an application and is using NSUserDefaults to store 'currentGameStatus' and would like to ask the following questions:

  1. How do i check if the NSUserDefaults .plist exists? Need this to determine if i need to create it for the first time and if so fill it with default values

  2. Where do i find it on my Mac (running simulator)? Would need to delete it to test if the first run works?

PeterK
  • 4,243
  • 4
  • 44
  • 74
  • 1
    In terms of your second question, see the existing [Easy way to see saved NSUserDefaults?](http://stackoverflow.com/questions/1676938/easy-way-to-see-saved-nsuserdefaults) question/answer. – John Parker Jan 23 '11 at 15:57

3 Answers3

22

you don't check.

you register your defaults. and if you haven't saved a value the default will be used.

NSDictionary *defaultUserDefaults = [NSDictionary dictionaryWithObjectsAndKeys:
                                     [NSNumber numberWithBool:NO], @"Foo",
                                     @"Bar", @"Baz",
                                     [NSNumber numberWithInteger:12], @"FooBar",
                                     nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:defaultUserDefaults];

and you do this every time your app launches.

Matthias Bauch
  • 89,811
  • 20
  • 225
  • 247
10

The way I do it is I set a BOOL flag in NSUserDefaults if it doesn't already exist:

if(![[NSUserDefaults standardUserDefaults] boolForKey:@"firstRun"]) {
   //do initialization stuff here...

   [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstRun"];
}
Jacob Relkin
  • 161,348
  • 33
  • 346
  • 320
  • what if later on, i set the first run to false? it will still get into the if statement and set back to YES – Kiddo Sep 25 '13 at 15:44
1
  1. NSUserDefaults already exists by default. You can add to it by [[NSUserDefaults standardUserDefaults] setObject:@"object" forKey:@"key"];

  2. You can find the NSUserDefaults .plist here alt text

timothy5216
  • 280
  • 5
  • 18