Har*_*h J 13 iphone xcode objective-c
我正在开发一款iPhone应用程序
我从root.plist中读取了一个键,如下所示:
NSString *Key1Var = [[NSUserDefaults standardUserDefaults] stringForKey:@"Key1"];
Run Code Online (Sandbox Code Playgroud)
("Key1"是PSMultiValueSpecifier
已在root.plist中设置了默认字符串值的)
一旦用户进行设置,这工作正常.但是如果用户在进行任何设置之前运行应用程序,他将获得nil
"Key1".在这种情况下,我期待我为"Key1"设置的默认值.我需要做什么,以便用户不必进行设置,以使应用程序第一次运行?
问候,哈里什
Mik*_*ler 14
请参阅此问题以获得完整的解决方案
您基本上想要在访问设置之前运行此代码:
- (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];
}
Run Code Online (Sandbox Code Playgroud)
这会将默认值加载到standardUserDefaults
对象中,这样您就不会再返回nil值,也不必复制代码中的默认设置.
归档时间: |
|
查看次数: |
10374 次 |
最近记录: |