如何注册用户默认使用NSUserDefaults而不覆盖现有值? [英] How to register user defaults using NSUserDefaults without overwriting existing values?

查看:248
本文介绍了如何注册用户默认使用NSUserDefaults而不覆盖现有值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个AppDelegate类与 +(void)initialize 方法,我用来注册一些默认值。这里是我使用的代码:

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];
}



我也创建了Preferences.xib,它保存了两个复选框( NSButton ),显示首选项的状态。它们绑定到具有相同键(在这种情况下为fooKey和barKey)的 NSUserDefaultsController 。每次启动应用程序并更改默认值时,都会在下次启动应用程序时恢复。

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.

有没有办法注册默认默认值 ?也许每次我构建和启动一个应用程序的首选项文件正在重新创建?也许我应该从 NSUserDefaultsController 解除绑定复选框,并用偏好窗口控制器中的一些自定义代码自己保持键的值?

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?

我使用的是Mac OS X 10.6.2和XCode 3.2.1

I'm using Mac OS X 10.6.2 and XCode 3.2.1

推荐答案

-registerDefaults:的文档中添加:


注册域的内容不会写入磁盘; 每次应用程序启动时都需要调用此方法。您可以将plist文件放在应用程序的Resources目录中,并调用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.

你的代码是在正确的轨道。这是您注册默认默认值的方式。

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

我通常在 -applicationDidFinishLaunching:

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

使用plist可以轻松添加和更改应用程序中的默认值,使用 @NO作为值的错误。

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.

这篇关于如何注册用户默认使用NSUserDefaults而不覆盖现有值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆