我有一个带有 +(void)initialize
方法的 AppDelegate 类,我用它来注册一些默认值。这是我使用的代码:
+ (void)initialize {
NSDictionary *defaults = [NSDictionary dictionaryWithObjectsAndKeys:@"NO", @"fooKey", @"YES", @"barKey", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:defaults];
}
我还创建了 Preferences.xib,其中包含几个显示首选项状态的复选框 (NSButton
)。它们使用相同的键(本例中为 fooKey 和 barKey)绑定(bind)到 NSUserDefaultsController 。每次我启动应用程序并更改“默认值”时,它们都会在下次应用程序启动时恢复。
有没有办法注册“默认默认值”而不覆盖已经存在的值?也许每次我构建并启动应用程序时,都会重新创建其首选项文件?也许我应该从 NSUserDefaultsController
取消绑定(bind)复选框,并使用首选项窗口 Controller 中的一些自定义代码自己维护键的值?
我想听听您选择的维护用户默认值的实现。
我使用的是 Mac OS X 10.6.2 和 XCode 3.2.1
最佳答案
来自 -registerDefaults 的文档:
(添加了重点):
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.
所以你的代码是在正确的轨道上。这是注册默认值的方式。
我通常在-applicationDidFinishLaunching:
中使用它:
// Load default defaults
[[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Defaults" ofType:@"plist"]]];
使用 plist 可以轻松地在应用中添加和更改默认值,并且还可以防止您犯下使用 @"NO"
作为值的错误。
编辑:Swift 3 变体:
UserDefaults.standard.register(defaults: NSDictionary(contentsOf: Bundle.main.url(forResource: "Defaults", withExtension: "plist")!)! as! [String : Any])
关于cocoa - 如何使用 NSUserDefaults 注册用户默认值而不覆盖现有值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2076816/