如何使用 NSUserDefaults 注册用户默认值而不覆盖现有值?
我有一个带有 +(void)initialize
方法的 AppDelegate 类,我用它来注册一些默认值。这是我使用的代码:
+ (void)initialize {
NSDictionary *defaults = [NSDictionary dictionaryWithObjectsAndKeys:@"NO", @"fooKey", @"YES", @"barKey", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:defaults];
}
我还创建了 Preferences.xib,其中包含几个显示首选项状态的复选框 (NSButton
)。它们使用相同的键(本例中为 fooKey 和 barKey)绑定到 NSUserDefaultsController 。每次我启动应用程序并更改“默认值”时,它们都会在下次应用程序启动时恢复。
有没有办法注册“默认默认值”而不覆盖已经存在的值?也许每次我构建并启动应用程序时,都会重新创建其首选项文件?也许我应该从 NSUserDefaultsController
取消绑定复选框,并使用首选项窗口控制器中的一些自定义代码自己维护键的值?
我想听听您选择的维护用户默认值的实现。
我使用的是 Mac OS X 10.6.2 和 XCode 3.2.1
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
来自
-registerDefaults:
的文档(添加了重点):所以你的代码是在正确的轨道上。这就是注册默认值的方式。
我通常在
-applicationDidFinishLaunching:
中使用它:使用 plist 可以轻松地在应用程序中添加和更改默认值,并且可以防止您犯下使用
@"NO"
的错误。 code> 也作为一个值。编辑:Swift 3 变体:
From the documentation for
-registerDefaults:
(emphasis added):So your code was on the right track. This is how you register default defaults.
I usually use this in
-applicationDidFinishLaunching:
: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: