iphone:Settings.bundle返回null值 [英] iphone : Settings.bundle returns null value

查看:95
本文介绍了iphone:Settings.bundle返回null值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用xCode 3.2然后转移到xCode 4.2并从Settings.bundle获取一些值...它工作正常。

I was using xCode 3.2 and then moved to xCode 4.2 and getting some values from Settings.bundle ... it was working fine.

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

Mean while I need to edit some values in Settings.bundle but The Root.plist file was not showing so I follow the below procedure but did not make any change in file.

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 而不是值。

After that I could see Root.plist but now could not get its values in application. Actually getting Null instead of value.

以下是Settings.bundle的代码和图片

Below is code and image of 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);
}

推荐答案

我得到了解决方案,只需调用以下代码即可applicationDidFinishLaunchingWithOptions用于初始化用户默认值。并且它的工作原理

I got the solution, just call the below code in applicationDidFinishLaunchingWithOptions to initialize User defaults. and it works

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

Replace somePropertyYouExpect in first line with property you stored in User Defaults.

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]; 
} 

这篇关于iphone:Settings.bundle返回null值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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