How to set initial values for NSUserDefault Keys?

前端 未结 4 994
轻奢々
轻奢々 2020-12-02 14:30

I want to set some initial values for my NSUserDefault keys so that the first run of the app has some reasonable initial settings. I thought I ran across a simple way to do

相关标签:
4条回答
  • 2020-12-02 14:46

    You should use the registerDefaults method of NSUserDefaults. Prepare a plist file in your bundle that contains the default preferences and then use that plist to register the defaults.

    NSString *defaultPrefsFile = [[NSBundle mainBundle] pathForResource:@"defaultPrefs" ofType:@"plist"];
    NSDictionary *defaultPreferences = [NSDictionary dictionaryWithContentsOfFile:defaultPrefsFile];
    [[NSUserDefaults standardUserDefaults] registerDefaults:defaultPreferences];
    

    You have to execute this code on every launch of your app. It will add these values to a separate domain in the user defaults hierarchy. Whenever your app's user defaults don't provide a value for a certain key, NSUserDefaults will fall back to this domain and retrieve the value from there.

    0 讨论(0)
  • 2020-12-02 14:51

    If you have many default values, let use ola's answer, otherwise this is good for a few params

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    
    if (![defaults boolForKey:USERDEFAULT_IS_INITIALIZED]) { 
        [defaults setBool:YES forKey:USERDEFAULT_IS_INITIALIZED];
    
        // Set initial values 
        ...
    
        [defaults synchronize];
    }
    
    0 讨论(0)
  • 2020-12-02 15:01
    -(void) loadDef
    {
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    
        _removeAd=[userDefaults boolForKey:SAVE_AD_STATUS];
    
        NSString* strDefSetting=[userDefaults stringForKey:SAVE_STATUS_ADSETTING];
        if(strDefSetting==nil
           ||[strDefSetting isEqualToString:@""]
           )
        {
            strDefSetting=@"0.5";
        }
    
        _floatAdmob=strDefSetting.floatValue;//0.5;
    }
    
    0 讨论(0)
  • 2020-12-02 15:07
    if ([[[[NSUserDefaults standardUserDefaults] dictionaryRepresentation] allKeys] containsObject:@"initialValuesHaveBeenWritten"])
    {
        [[NSUserDefaults standardUserDefaults] setValue:obj1 forKey:key1];
        [[NSUserDefaults standardUserDefaults] setValue:obj2 forKey:key2];
    
    
        [[NSUserDefaults standardUserDefaults] setValue:obj1 forKey:@"initialValuesHaveBeenWritten"];
    
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    

    NB: Not tested, done from memory

    0 讨论(0)
提交回复
热议问题