从Settings.bundle plist文件中注册默认设置? [英] Register default settings from the Settings.bundle plist file?

查看:85
本文介绍了从Settings.bundle plist文件中注册默认设置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将Settings.bundle文件添加到我的iOS应用程序中.一两个设置非常少. Settings.bundle中的plist文件为Settings应用程序指定默认值.我读过,要使我的iOS应用程序了解这些默认值,还必须将它们编码到我的应用程序中.这似乎是在重复自己,并为默认设置留出了空缺,以便在我修改程序时很容易失去同步.

I'm adding a Settings.bundle file to my iOS application. It's very minimal with one or two settings. The plist file in the Settings.bundle specifies the defaults, to the Settings application. I've read that to make my iOS application aware of these defaults, I have to also code them into my application. This seems like repeating myself and leaving an opening for defaults to easily get out of sync as I modify the program.

我知道我可以使用plist文件的内容注册默认值,如下所示:

I know I can register the defaults using the contents of plist file, like so:

[[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Defaults" ofType:@"plist"]]];

不过,这似乎又是在重复自己.可以将Settings.bundle中的plist文件用作这些默认值的来源,以便仅在1个位置指定默认值吗?

That also seems like repeating myself, though. Would it be possible to use the plist file from the Settings.bundle as the source of these defaults, so that I only specify defaults in 1 location?

我真正调整了负载,使其看起来像这样:

I trued adjusting that load to look something like this:

[[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Settings.bundle/Root" ofType:@"plist"]]];

但这没有用.有人知道这是否可行,以及如何加载该plist文件吗?

That did not work, though. Does anybody know if this is possible, and how to load that plist file?

推荐答案

希望将其添加为对Andy的回答的注释,但是Stack Overflow并没有让我(对于注释来说太长了.).
如果您使用的是ObjC,请使用以下版本:

Wanted to add this as a comment to Andy's answer, but Stack Overflow didn't let me (too long for a comment).
If you're using ObjC here's your version:

-(void)registerDefaults
{
    NSString* pathString = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"Settings.bundle"];
    NSString* rootPath = [pathString stringByAppendingPathComponent:@"Root.plist"];
    NSDictionary* settingsDict = [NSDictionary dictionaryWithContentsOfFile:rootPath];
    NSArray* prefSpecifiers = settingsDict[@"PreferenceSpecifiers"] ;

    NSMutableDictionary* defaults = [NSMutableDictionary dictionary];

    for (NSDictionary* item in prefSpecifiers) {
        NSString* theKey = item[@"Key"];
        NSObject* defaultValue = item[@"DefaultValue"];

        if (defaultValue && theKey) {
            defaults[theKey] = defaultValue;
        }

    }

    if (defaults.count > 0) {
        [[NSUserDefaults standardUserDefaults] registerDefaults:defaults];
    }

}

这篇关于从Settings.bundle plist文件中注册默认设置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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