Recipe #2: Initializing user preferences using NSUserDefaults

16
Jan
2

Recently I was in need of some user preferences. I read a guide on user defaults programming. Everything seemed easy and clear, but I still couldn’t find the thing that interested me most – initializing user preferences. By “initialization” I mean set defaults once so they can be overridden by user and not set again. For some reason I thought that I’d have to check each preferences key for its existence and set it accordingly.

Then the light bulb lit above my spiky head. I present you with the solution:

// Place this code into your apps delegate class
+ (void)initialize {
  NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
 
  // initialize the dictionary with default values
  NSDictionary *appDefaults = [NSDictionary dictionaryWithObjectsAndKeys:@"fooValue", @"fooKey", @"barValue", @"barKey", nil];
 
  // and set them appropriately
  [defaults registerDefaults:appDefaults];
}

Now for refactored and more comfortable version you should use a separate plist for initializing user defaults. I believe it’s easier to add a row to plist file than add key/value pair into dictionary:

+ (void)initialize {
  // get the filename for "default defaults"
  NSString *defaultsFilename = [[NSBundle mainBundle] pathForResource:@"Defaults" ofType:@"plist"];
 
  // initialize a dictionary with contents of it
  NSDictionary *defaults = [NSDictionary dictionaryWithContentsOfFile:defaultsFilename];
 
  // register the stuff
  [[NSUserDefaults standardUserDefaults] registerDefaults:defaults];
}

The advantage of this approach is that even after updates to your app even unset defaults will be initialized (in case of newly added preferences).

That’s it! Kudos goes to Laurent Etiemble and Johan Kool for their answers to my question.

Enjoy this article?

Consider subscribing to our RSS feed!

2 Comments

  1. Ricky
    18:36 on February 5th, 2010

    So what do you think of Apple’s example in their AppPrefs sample code? That’s what I’m currently using but it makes updating the app (with new preferences) a little difficult. Do you just use this? Also, do you use the Settings bundle with this or do you update the preferences yourself from within the app?

  2. eimantas
    11:08 on February 6th, 2010

    I haven’t checked out the Apple sample code, but yes, so far – I’m using only this. And as a separate Settings bundle (e.g. Preferences.xib).

Leave a comment

RSS feed for comments on this post