我正在开发 iPhone 应用
我像这样从 root.plist 中读取了一个 key :
NSString *Key1Var = [[NSUserDefaults standardUserDefaults] stringForKey:@"Key1"];
(“Key1”是一个 PSMultiValueSpecifier
,其默认字符串值已在 root.plist 中设置)
一旦用户进行设置,效果很好。
但是,如果用户在进行任何设置之前运行该应用程序,他将获得“Key1”的 nil
。
在这种情况下,我期待我为“Key1”设置的默认值。
我需要做什么,
让用户不必做设置,让应用程序第一次运行?
问候, 哈里什
最佳答案
参见 this question以获得完整的解决方案。
您基本上想在访问设置之前运行此代码:
- (void)registerDefaultsFromSettingsBundle {
NSString *settingsBundle = [[NSBundle mainBundle] pathForResource:@"Settings" ofType:@"bundle"];
if(!settingsBundle) {
NSLog(@"Could not find Settings.bundle");
return;
}
NSDictionary *settings = [NSDictionary dictionaryWithContentsOfFile:[settingsBundle stringByAppendingPathComponent:@"Root.plist"]];
NSArray *preferences = [settings objectForKey:@"PreferenceSpecifiers"];
NSMutableDictionary *defaultsToRegister = [[NSMutableDictionary alloc] initWithCapacity:[preferences count]];
for(NSDictionary *prefSpecification in preferences) {
NSString *key = [prefSpecification objectForKey:@"Key"];
if(key) {
[defaultsToRegister setObject:[prefSpecification objectForKey:@"DefaultValue"] forKey:key];
}
}
[[NSUserDefaults standardUserDefaults] registerDefaults:defaultsToRegister];
[defaultsToRegister release];
}
这会将默认值加载到 standardUserDefaults
对象中,因此您将不再返回 nil 值,并且您不必在代码中复制默认设置。
关于iPhone App : How to get default value from root. plist?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1431148/