DefaultValue of Settings.bundle doesn't work? (NSUserDefaults)

7227 단어 NSUserDefaults
The first time I need to use the iPhone system configuration, I found that the DefaultValue in Settings.bundle/Rool.plist does not work. The return is nil. Google, NSUserDefaults does not provide a ready-made method to make DefaultValue take effect. The solution is as follows:
Detect the set item value in the program's - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{}, if it is nil, set it to the value of 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://stack overflow.com/questions/510216/miserable-have-mark-he-and-settings-in-settings-bundle-default-even-if-have-don't-open-he-and-is

좋은 웹페이지 즐겨찾기