iPhone和NSUserDefaults [英] iPhone and NSUserDefaults

查看:145
本文介绍了iPhone和NSUserDefaults的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 viewWillLoad:方法中,我目前正在做以下几行:

In my viewWillLoad: method I'm currently doing something along these lines:

- (void)viewWillAppear:(BOOL)animated {
   NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
   if ( [defaults boolForKey:@"enabled_preference"] ) {
      ...   
   } else {
      ...   
   }
   [super viewWillAppear:animated];
}

如果我在打开首选项窗格之前构建并运行应用程序(使用正常的 Settings.bundle )那么bool似乎是 NO (或者更可能是 nil )而不是默认的 YES 。但是,如果在打开应用程序之前打开设置应用程序并查看应用程序首选项窗格,则一切都按预期工作。

If I build and run the application before opening the preference pane (built using a normal Settings.bundle) then the bool seems to be NO (or more probably nil) rather than the default YES. However if I open the Settings application and look at the application preference pane before I open the application, everything works as expected.

我假设应用程序首选项未初始化,我应该将它们初始化为应用程序委托中的默认值(如果尚未设置)。有人可以证实吗?或者我错过了其他一些令人眼花缭乱明显的东西?

I'm presuming that the application preferences aren't initialized and I should initialise them to the default value (if not already set) in the application delegate. Can someone confirm this? Or am I missing something else blindingly obvious here?

推荐答案

您应该使用在代码中提供默认值 - registerDefaults:。这通常在 + initialize 方法中完成,无论哪个类使用这些设置。请参阅使用NSUserDefaults

You should provide defaults in your code using -registerDefaults:. This is typically done in an +initialize method for whatever class uses the settings. See Using NSUserDefaults.

这篇关于iPhone和NSUserDefaults的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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