iphone:Settings.bundle返回null值

时间:2012-10-04 10:34:02

标签: iphone objective-c ios xcode ipad

我正在使用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 而不是值。

以下是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);
}

enter image description here

2 个答案:

答案 0 :(得分: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]; 
} 

答案 1 :(得分: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);
    }

OR

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

iPhone - reading Setting.bundle returns wrong values

NSUserDefaults Settings Bundle Plist