设置捆绑 - 默认值行为? [英] settings bundle - default value behaviour?

查看:102
本文介绍了设置捆绑 - 默认值行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



当我的应用程序启动并且我检索的值为null时,我将创建一个包含单个偏好值的设置包, 。在用户提供值之前,我必须手动编写要使用的值吗?



此外,如果用户在首选项屏幕上输入文本字段,没有进行任何更改,值将不会设置...用户必须实际更改要保存的值,是否正确?

解决方案

不,不要这样做。



这里有一个函数:

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


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?

解决方案

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

这篇关于设置捆绑 - 默认值行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆