Set bundle - default behavior?

I created a parameter set with one preference value, a text box with a default value.

When my application starts up and I get the value, it is null. Do I have to manually encode the value to use before the user provides the value?

Also, if the user does this on the settings screen and enters the text field, leave it without making any changes, the value will not be set ... the user must actually change the value to save it, this is correct

+5
source share
3 answers

No, do not do this.

There is a function for this:

id userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults registerDefaults: defaultSettings];

, PreferenceSpecifiers plist.

- :

- (NSDictionary *)readDefaultSettingsFromPlist: (NSString *)inPath;
{
    id mutable = [NSMutableDictionary dictionary];
    id settings = [NSDictionary dictionaryWithContentsOfFile: inPath];
    id specifiers = [settings objectForKey: @"PreferenceSpecifiers"];
    for (id prefItem in specifiers) {
        id key = [prefItem objectForKey: @"Key"];
        id value = [prefItem objectForKey: @"DefaultValue"];
        if ( key && value ) {
            [mutable setObject: value
                        forKey: key];
        }
    }
    return [NSDictionary dictionaryWithDictionary: mutable];
}
+4

, , .

+1

, "", NSUserDefaults standardUserDefaults. , , .

- :

+ (NSString *)userDefaultStringForKey:(NSString *)key defaultValue:(NSString *)def {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *val = [defaults stringForKey:key];
    if (val == nil && def != nil) {
        val = def;
        [defaults setObject:val forKey:key];
    }
    return val;
}
+1

All Articles