How to register user defaults using NSUserDefaults without overwriting existing values?

守給你的承諾、 提交于 2019-11-26 17:58:50

问题


I have an AppDelegate class with +(void)initialize method that I use to register some defaults. Here's the code that I use:

+ (void)initialize {
  NSDictionary *defaults = [NSDictionary dictionaryWithObjectsAndKeys:@"NO", @"fooKey", @"YES", @"barKey", nil];

  [[NSUserDefaults standardUserDefaults] registerDefaults:defaults];
}

I also created Preferences.xib which holds couple of checkboxes (NSButton) that display status of preferences. They are bound to NSUserDefaultsController with same keys (fooKey and barKey in this case). Each time I launch an app and change the "defaults" they are restored on next app launch.

Is there a way to register "default defaults" without overwriting already existing values? Maybe each time I build and launch an app its preferences file is being recreated? Maybe I should unbind checkboxes from NSUserDefaultsController and maintain the values of keys myself with some custom code in preferences window controller?

I'd like to hear your implementation of choice for maintaining user defaults.

I'm using Mac OS X 10.6.2 and XCode 3.2.1


回答1:


From the documentation for -registerDefaults: (emphasis added):

The contents of the registration domain are not written to disk; you need to call this method each time your application starts. You can place a plist file in the application's Resources directory and call registerDefaults: with the contents that you read in from that file.

So your code was on the right track. This is how you register default defaults.

I usually use this in -applicationDidFinishLaunching::

// Load default defaults
[[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Defaults" ofType:@"plist"]]];

Using a plist makes it easy to add and change defaults in your app, and it prevents you from making the mistake of using @"NO" as a value too.

Edit: Swift 3 variant:

 UserDefaults.standard.register(defaults: NSDictionary(contentsOf: Bundle.main.url(forResource: "Defaults", withExtension: "plist")!)! as! [String : Any])


来源:https://stackoverflow.com/questions/2076816/how-to-register-user-defaults-using-nsuserdefaults-without-overwriting-existing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!