How to set default values for NSUserDefaults
NSUserDefaults is a great place to store your apps settings. It is convenient, available everywhere, and integrates nicely with settings bundles. One problem you run across with NSUserDefaults, is setting default values for your settings. There is a very simple elegant solution to this, detailed below.
I usually have one header file just for keys I use throughout the project.
Create a defaults property list
Create a new property list, and enter default values for all your settings. Make sure the keys match the ones you #define-d. Also pay attention to the types.
Set defaults on launch
The following code needs to run every time your app launches (in case your NSUserDefaults have gotten nuked or mangled). I added the following three lines to
application:didFinishLaunchingWithOptions: in my app delegate.
NSString *defPath = [[NSBundle mainBundle] pathForResource:@"DEF" ofType:@"plist"];
NSDictionary *defaultsDict = [NSDictionary dictionaryWithContentsOfFile:defPath];
[[NSUserDefaults standardUserDefaults] registerDefaults:defaultsDict];
Fantastic, you are done.