iPhone App : How to get default value from root.plist?

前端 未结 7 2051
情深已故
情深已故 2020-12-14 04:09

I am working on an iPhone app

I read a key from root.plist like this :

NSString *Key1Var = [[NSUserDefaults standardUserDefaults] stringForKey:@\"Key         


        
7条回答
  •  一生所求
    2020-12-14 04:41

    See this question for a complete solution.

    You essentially want to run this code before accessing the setting:

    - (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];
    }
    

    This will load the default values into the standardUserDefaults object so you will no longer get back nil values, and you don't have to duplicate the default settings in your code.

提交回复
热议问题