PeterK
PeterK

Reputation: 4301

How to check if NSUserDefaults exist

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?

Upvotes: 6

Views: 6740

Answers (3)

Matthias Bauch
Matthias Bauch

Reputation: 90127

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.

Upvotes: 22

Jacob Relkin
Jacob Relkin

Reputation: 163318

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"];
}

Upvotes: 10

timothy5216
timothy5216

Reputation: 281

  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

Upvotes: 1

Related Questions