Settings.bundle的DefaultValue不起作用?(NSUserDefaults)
时间:2010-12-29 来源:Elf Sundae
在程序的- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{}中检测设置的项值,如果为nil就全部设为DefaultValue的值:
// [YourApp]AppDelegate.m
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSString *name = [[NSUserDefaults standardUserDefaults]
stringForKey:@"name_preference"];
if(!name) {
// 加载默认配置
[self performSelector:@selector(registerDefaultsFromSettingsBundle)];
}
[window addSubview:viewController.view];
[window makeKeyAndVisible];
return YES;
}
// 获取默认设置
- (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];
}
Download DefaultSettingsDemo
相关阅读 更多 +