3

我使用的是 xCode 3.2,然后移至 xCode 4.2 并从 Settings.bundle 获取一些值......它工作正常。

同时,我需要在 Settings.bundle 中编辑一些值,但 Root.plist 文件没有显示,所以我按照以下步骤操作,但没有对文件进行任何更改。

1) Click on the Settings.Bundle file, go over to the utilities window,
and look in the File Inspector.
2) Using the drop-down, change the file type to 'Application Bundle'

之后我可以看到 Root.plist 但现在无法在应用程序中获取它的值。实际上得到Null而不是 value。

下面是 Settings.bundle 的代码和图像

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
host = [defaults stringForKey:@"meter_preference"];
if(host == nil)
{
    host = @"10.20.20.1";
    DDLogError(@"Meter host is nil from NSUserDefaults, defaulting to %@", host);
}

在此处输入图像描述

4

2 回答 2

4

我得到了解决方案,只需在 applicationDidFinishLaunchingWithOptions 中调用以下代码来初始化用户默认值。它有效

用您存储在用户默认值中的属性替换somePropertyYouExpect第一行。

if (![[NSUserDefaults standardUserDefaults] objectForKey:@"somePropertyYouExpect"])  {

    NSString  *mainBundlePath = [[NSBundle mainBundle] bundlePath];
    NSString  *settingsPropertyListPath = [mainBundlePath
                                           stringByAppendingPathComponent:@"Settings.bundle/Root.plist"];

    NSDictionary *settingsPropertyList = [NSDictionary 
                                          dictionaryWithContentsOfFile:settingsPropertyListPath];

    NSMutableArray      *preferenceArray = [settingsPropertyList objectForKey:@"PreferenceSpecifiers"];
    NSMutableDictionary *registerableDictionary = [NSMutableDictionary dictionary];

    for (int i = 0; i < [preferenceArray count]; i++)  { 
        NSString  *key = [[preferenceArray objectAtIndex:i] objectForKey:@"Key"];

        if (key)  {
            id  value = [[preferenceArray objectAtIndex:i] objectForKey:@"DefaultValue"];
            [registerableDictionary setObject:value forKey:key];
        }
    }

    [[NSUserDefaults standardUserDefaults] registerDefaults:registerableDictionary]; 
    [[NSUserDefaults standardUserDefaults] synchronize]; 
} 
于 2012-10-10T06:13:47.040 回答
1

从你的代码,试试这个想法..

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    host = [defaults stringForKey:@"meter_preference"];
    if(!host == nil)
    {
        host = @"10.20.20.1";
        DDLogError(@"Meter host is nil from NSUserDefaults, defaulting to %@", host);
    }

或者

查看此链接可能会对您有所帮助...

iPhone - 读取 Setting.bundle 返回错误值

NSUserDefaults 设置捆绑列表

于 2012-10-04T10:53:37.667 回答