设置包 - 默认值行为?

Nip*_*rus 5 cocoa-touch settings-bundle ios

我创建了一个包含单个首选项值的设置包,一个带有默认值的文本字段.

当我的应用程序启动并检索该值时,它为null.在用户提供值之前,是否必须手动编写要使用的值?

此外,如果用户进入首选项屏幕并输入文本字段,则保留它而不进行任何更改,将不会设置该值...用户必须实际更改要保存的值,这是正确的吗?

Ste*_*her 4

不,不要这样做。

有一个函数可以做到这一点:

id userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults registerDefaults: defaultSettings];
Run Code Online (Sandbox Code Playgroud)

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];
}
Run Code Online (Sandbox Code Playgroud)