views:

609

answers:

2

In my viewWillLoad: method I'm currently doing something along these lines:

- (void)viewWillAppear:(BOOL)animated {
   NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
   if ( [defaults boolForKey:@"enabled_preference"] ) {
      ...   
   } else {
      ...   
   }
   [super viewWillAppear:animated];
}

If I build and run the application before opening the preference pane (built using a normal Settings.bundle) then the bool seems to be NO (or more probably nil) rather than the default YES. However if I open the Settings application and look at the application preference pane before I open the application, everything works as expected.

I'm presuming that the application preferences aren't initialized and I should initialise them to the default value (if not already set) in the application delegate. Can someone confirm this? Or am I missing something else blindingly obvious here?

+1  A: 

You should provide defaults in your code using -registerDefaults:. This is typically done in an +initialize method for whatever class uses the settings. See Using NSUserDefaults.

Rob Napier
Thanks, adding the +initialize { } method did the trick.
Alasdair Allan
+2  A: 

Using the initialize method works but I like this other answer on stackoverflow that has code to read the default values from the bundle and uses them to initialize the defaults. That way you don't have to hardcode the default settings in the code, they are in the plist where they belong.

progrmr
Yup. This is pretty much what I ended up doing in the end although it's a big gapping hole in the API that we have to do this. Objective-C is all about not having to write huge chunks of make-work code after all.
Alasdair Allan