我有一个带有 settings.bundle 的 iPhone 应用程序,可以处理我的应用程序的各种设置。我可以在 root.plist 文件中设置默认值(使用 DefaultValue 属性),但这些值仅在用户第一次打开设置应用程序时使用。有什么方法可以在安装应用程序时写出这些值吗?我知道我可以编写代码来检查应用程序的首次启动,然后将它们写出来,但它们会位于两个不同的位置。
以下是我的 root.plist 中的一个条目作为示例:
<dict>
<key>Type</key>
<string>PSToggleSwitchSpecifier</string>
<key>Title</key>
<string>Open To Top Location</string>
<key>Key</key>
<string>open_top_location</string>
<key>DefaultValue</key>
<string>YES</string>
<key>TrueValue</key>
<string>YES</string>
<key>FalseValue</key>
<string>NO</string>
</dict>
最终结果应该是,如果我询问“open_to_top_location”,我会得到一个“是”,而不是直到用户第一次打开“设置”应用程序时它才出现。
有任何想法吗?
如果我理解正确,您希望避免指定两次默认值(一次作为 Settings.bundle/Root.plist 文件中的“DefaultValue”键,一次作为应用程序初始化代码中的“DefaultValue”键),因此您不必将它们保留在同步。
由于 Settings.bundle 存储在应用程序包本身中,因此您只需读取那里给出的默认值即可。我整理了一些示例代码,这些代码查看“设置”包并读取其中每个键的默认值。请注意,这不会写出默认键;如果它们不存在,您需要在每次启动时读取并注册它们(请随意更改此设置)。我只做了一些粗略的测试,所以请确保它在所有情况下都适合您。
- (void)applicationDidFinishLaunching:(UIApplication *)application {
NSString *name = [[NSUserDefaults standardUserDefaults] stringForKey:@"name"];
NSLog(@"name before is %@", name);
// Note: this will not work for boolean values as noted by bpapa below.
// If you use booleans, you should use objectForKey above and check for null
if(!name) {
[self registerDefaultsFromSettingsBundle];
name = [[NSUserDefaults standardUserDefaults] stringForKey:@"name"];
}
NSLog(@"name after is %@", name);
}
- (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 && [[prefSpecification allKeys] containsObject:@"DefaultValue"]) {
[defaultsToRegister setObject:[prefSpecification objectForKey:@"DefaultValue"] forKey:key];
}
}
[[NSUserDefaults standardUserDefaults] registerDefaults:defaultsToRegister];
[defaultsToRegister release];
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)