iPhone App : How to get default value from root. plist?

标签 iphone objective-c xcode

我正在开发 iPhone 应用

我像这样从 root.plist 中读取了一个 key :

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

(“Key1”是一个 PSMultiValueSpecifier,其默认字符串值已在 root.plist 中设置)

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

问候, 哈里什

最佳答案

参见 this question以获得完整的解决方案。

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

- (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 对象中,因此您将不再返回 nil 值,并且您不必在代码中复制默认设置。

关于iPhone App : How to get default value from root. plist?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1431148/

相关文章:

ios - 导出 IPA 进行测试而不是 Appstore 与(临时)

iphone - Cocos2d iPhone : Rotate Sprite using Accelerometer

ios - AFHTTPRequestOperation 与 AFHTTPRequestOperationManager

html - 带有 block 引号的 html 中的 NSAttributedString

ios - iPad 3 4G 不显示 url 图片

iphone - 标签栏和导航 Controller 内的 MKMapView 隐藏了 Google 品牌

iphone - 动画 UIView - 如何跟踪位置?

ios - 找不到“OpenTok/OpenTok.h”文件

objective-c - 为什么 waitUntilAllOperationsAreFinished 不在此代码中等待?

iphone - UIWebView 中的谷歌地图从核心传递数据