Settings.bundle的DefaultValue不起作用?(NSUserDefaults)

第一次需要用iPhone系统配置,发现Settings.bundle/Rool.plist中的DefaultValue不起作用。返回是nil。Google了下,NSUserDefaults确实没有提供现成的方法去让DefaultValue生效。解决办法如下:

在程序的- (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

 

Ref:http://stackoverflow.com/questions/510216/can-you-make-the-settings-in-settings-bundle-default-even-if-you-dont-open-the-s

posted @ 2010-12-29 17:15  Elf Sundae  阅读(2039)  评论(0编辑  收藏  举报