Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set initial values for NSUserDefault Keys?

I want to set some initial values for my NSUserDefault keys so that the first run of the app has some reasonable initial settings. I thought I ran across a simple way to do this in the app bundle .plist, but now I can't find it. Any ideas?

like image 730
Suz Avatar asked Dec 12 '11 12:12

Suz


2 Answers

You should use the registerDefaults method of NSUserDefaults. Prepare a plist file in your bundle that contains the default preferences and then use that plist to register the defaults.

NSString *defaultPrefsFile = [[NSBundle mainBundle] pathForResource:@"defaultPrefs" ofType:@"plist"]; NSDictionary *defaultPreferences = [NSDictionary dictionaryWithContentsOfFile:defaultPrefsFile]; [[NSUserDefaults standardUserDefaults] registerDefaults:defaultPreferences]; 

You have to execute this code on every launch of your app. It will add these values to a separate domain in the user defaults hierarchy. Whenever your app's user defaults don't provide a value for a certain key, NSUserDefaults will fall back to this domain and retrieve the value from there.

like image 174
Ole Begemann Avatar answered Sep 19 '22 23:09

Ole Begemann


If you have many default values, let use ola's answer, otherwise this is good for a few params

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];  if (![defaults boolForKey:USERDEFAULT_IS_INITIALIZED]) {      [defaults setBool:YES forKey:USERDEFAULT_IS_INITIALIZED];      // Set initial values      ...      [defaults synchronize]; } 
like image 29
thanhbinh84 Avatar answered Sep 19 '22 23:09

thanhbinh84