settings bundle - default value behaviour?

跟風遠走 提交于 2019-12-21 16:05:37

问题


I have created a settings bundle with a single preference value, a text field with a default value.

When my application launches and I retrieve the value it is null. Do I have to manually code the value to use before the user has provided a value?

Also if the user does to the preferences screen and enters the text field then leave it without making any changes the value will not be set ... the user has to actually change the value for it to be saved, is this correct?


回答1:


No, don't do that.

There's a function for this:

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

You can build the parameter by iterating all the sub keys of PreferenceSpecifiers in your settings plist file.

Something like this:

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



回答2:


You can check in your app if you are getting null for key then you can use your own default value.




回答3:


It seems the default value is shown in the Settings App, but is not automatically stored in NSUserDefaults standardUserDefaults. So if you find a nil value you should set the default value explicitly.

Something like this:

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


来源:https://stackoverflow.com/questions/5631090/settings-bundle-default-value-behaviour

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!