iphone : Settings. 包返回空值

标签 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

最佳答案

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

将第一行的 somePropertyYouExpect 替换为您在 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. 包返回空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12725372/

相关文章:

iphone - iPad 大型 NSArray - initWithObjects 与 ArrayWithObjects

objective-c - Xcode 4.1 多点触控手势改变

ios - Objective C - 带动画的自定义 UIView 类初始化

ios - Dealloc 导致在 Cocos2D 场景之间切换时发生崩溃

iphone - resignFirstResponder 不会关闭键盘

ios - 如何在所有符合条件的 iOS 应用程序中共享 PDF 文件?

iphone - 使用 Xcode 和 SDK 4+ 构建胖静态库(设备 + 模拟器)

ios - 可以将委托(delegate)变量分配给调用对象吗?

ios - 从 UILabel 文本掩码获取 PDF

ios - Xcode 8 - 删除了一些按钮边框