设置包默认值不会被设置
我有一个iOS应用程序,使用一个settings.bundle来处理我的应用程序的各种设置。 我将root.plist文件中的默认值(使用DefaultValue属性)设置为YES
但是在应用程序在设备或iOS模拟器上启动时,所有值均为NO
。 它只在第一次发射时运行良好。
我正在检索这个代码的默认值(我在这里做错了什么?):
NSUserDefaults *localeDefaults = [NSUserDefaults standardUserDefaults]; BOOL ENWORDS = [localeDefaults boolForKey:@"localetime"];
问题是types的default Value
必须是boolean
不string
;)删除此值并添加另一个default Value
属性再次希望这有助于
默认值由Settings.app使用,仅用于显示目的。 如果您不更改设置应用程序中的值,则不会保存到NSUserDefaults。
你必须自己注册默认值。 在application:didFinishLaunchingWithOptions:
使用这样的东西application:didFinishLaunchingWithOptions:
::
NSDictionary *userDefaultsDefaults = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithBool:YES], @"localetime", nil]; [[NSUserDefaults standardUserDefaults] registerDefaults:userDefaultsDefaults];
这个博客文章可能有帮助: http : //greghaygood.com/2009/03/09/updating-nsuserdefaults-from-settingsbundle
tl; dr – 直到用户打开设置页面,然后默认值不会被复制到您的应用程序中。 这是苹果公司的预期行为。
我个人认为这太可怕了。 这意味着您将不得不在代码中设置默认值,以防用户启动您的应用程序而无需首先进入设置页面(对于大约99%的用例来说,这是正确的!)
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { //< Register Defaults NSString *settingsBundlePath = [[NSBundle mainBundle] pathForResource:@"Settings" ofType:@"bundle"]; NSBundle *settingsBundle = [NSBundle bundleWithPath:settingsBundlePath]; NSString *rootPlistPath = [settingsBundle pathForResource:@"Root" ofType:@"plist"]; NSDictionary *settingsDict = [[NSDictionary alloc] initWithContentsOfFile:rootPlistPath]; NSArray *settingsItems = [settingsDict objectForKey:@"PreferenceSpecifiers"]; NSMutableDictionary *defaultDict = [NSMutableDictionary new]; for (NSDictionary *itemDict in settingsItems) { if ([itemDict objectForKey:@"DefaultValue"]) { [defaultDict setObject:[itemDict objectForKey:@"DefaultValue"] forKey:[itemDict objectForKey:@"Key"]]; } } [[NSUserDefaults standardUserDefaults] registerDefaults:defaultDict]; //< Following Code }
您可以通过获取objectForKey并检查是否为零来检查值是否已设置。
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; id dataExists = [userDefaults objectForKey:@"light_switch"]; BOOL lightSwitch; if (dataExists != nil) { lightSwitch = [userDefaults boolForKey:@"light_switch"]; NSLog(@"light_switch is %d", validateCertificates); } else { lightSwitch = YES; // default value NSLog(@"light_switch not set, default value is %d", validateCertificates); }