iPhone应用程序:如何从root.plist获取默认值? [英] iPhone App : How to get default value from root.plist?

查看:269
本文介绍了iPhone应用程序:如何从root.plist获取默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用iPhone应用程序

I am working on an iPhone app

我从root.plist读取了一个密钥,如下所示:

I read a key from root.plist like this :

NSString *Key1Var = [[NSUserDefaults standardUserDefaults] stringForKey:@"Key1"];

(Key1是 PSMultiValueSpecifier 已经在root.plist中设置了默认字符串值)

("Key1" is a PSMultiValueSpecifier for which a default string value has been set already in root.plist)

一旦用户进行设置,该工作正常。
但是如果用户在进行任何设置之前运行应用程序,他将为Key1获得 nil
在这种情况下,我期待我为Key1设置的默认值。
我需要做什么,
以便用户不必进行设置,让应用程序第一次运行?

That works fine, once the user makes settings. But if the user runs the app before he does any setting, he will get nil for "Key1". In such case, I was expecting the default value that i had set for "Key1". what i need to do, so that the user does not have to do setting, to make application run for the first time?

问候,
Harish

Regards, Harish

推荐答案

参见 this question for a complete solution。

See this question for a complete solution.

您基本上想要在访问设置之前运行此代码:

You essentially want to run this code before accessing the setting:

- (void)registerDefaultsFromSettingsBundle {
    NSString *settingsBundle = [[NSBundle mainBundle] pathForResource:@"Settings" ofType:@"bundle"];
    if(!settingsBundle) {
        NSLog(@"Could not find Settings.bundle");
        return;
    }

    NSDictionary *settings = [NSDictionary dictionaryWithContentsOfFile:[settingsBundle stringByAppendingPathComponent:@"Root.plist"]];
    NSArray *preferences = [settings objectForKey:@"PreferenceSpecifiers"];

    NSMutableDictionary *defaultsToRegister = [[NSMutableDictionary alloc] initWithCapacity:[preferences count]];
    for(NSDictionary *prefSpecification in preferences) {
        NSString *key = [prefSpecification objectForKey:@"Key"];
        if(key) {
            [defaultsToRegister setObject:[prefSpecification objectForKey:@"DefaultValue"] forKey:key];
        }
    }

    [[NSUserDefaults standardUserDefaults] registerDefaults:defaultsToRegister];
    [defaultsToRegister release];
}

这会将默认值加载到 standardUserDefaults object,这样您就不会再获取nil值,也不必复制代码中的默认设置。

This will load the default values into the standardUserDefaults object so you will no longer get back nil values, and you don't have to duplicate the default settings in your code.

这篇关于iPhone应用程序:如何从root.plist获取默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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