【问题标题】:Parse plist file and get value for key解析 plist 文件并获取键的值
【发布时间】:2013-05-27 14:41:30
【问题描述】:

我在下面有这个文件:

我有一个问题,如何从这个 plist 文件中获取 url 值。

我已将此文件转换为 NSDictionary,它包含所有键和值。

我添加了这一行来检查它是如何工作的

 NSLog(@"%@", [[[[source objectForKey:@"Root"] objectForKey:@"updates"] objectForKey:@"Item 0"] objectForKey:@"url"]);

但它返回 (null) 而不是 someurl1。

source - 这是我的 NSDictionary 实例变量。

我的 NSDictionary 对象的这个日志

(NSDictionary *) $1 = 0x0ab38b60 {
    plist =     {
        dict =         {
            array =             {
                dict =                 (
                                        {
                        integer = 4;
                        key =                         (
                            id,
                            url,
                            compression
                        );
                        string = "http://someurl1";
                        true = "";
                    },
                                        {
                        integer = 5;
                        key =                         (
                            id,
                            url,
                            compression
                        );
                        string = "http://someurl2";
                        true = "";
                    }
                );
            };
            key = updates;
        };
        version = "1.0";
    };
}

【问题讨论】:

  • objectForKey: 无法访问数组的项。 Item 0可以通过objectAtIndex:访问。
  • 感谢您的回复。我试过 NSLog(@"%@", [[[[source objectForKey:@"Root"] objectForKey:@"updates"] objectAtIndex:0] objectForKey:@"url"]);但它仍然输出 null
  • [source objectForKey:@"Root"] 输出什么?您可能不需要按名称获取该对象 - 毕竟它是根对象。

标签: ios xml plist nsdictionary


【解决方案1】:

试试:

for (NSDictionary *item in [source objectForKey:@"updates"]) {

    NSLog(@"%@", [item objectForKey:@"url"]);
}

请注意,'Root' 不是键,它只是 Xcode 显示 plist 的方式。而且您需要遍历一个数组,同样,“Item 0”就是它在 IDE 中的显示方式。

【讨论】:

  • 我已经用 NSLog 为我的 NSDictionary 更新了我的问题。可能是键的一些问题。
  • NSLog(@"%@", [source objectForKey:@"updates"]);也返回 null
  • 您的字典日志与 Xcode 屏幕截图的相似度为零。您加载了不同的 plist 或者您是如何加载的?
  • 我试过这个 NSDictionary *rootDictionary = [NSDictionary dictionaryWithContentsOfFile: [[NSBundle mainBundle] pathForResource:@"PListFile" ofType:@"plist"]];它有效。无论如何感谢您的帮助。这是我获取字典的错误
【解决方案2】:

很好。

试试这个代码。

NSDictionary *rootDictionary = [NSDictionary dictionaryWithContentsOfFile: [[NSBundle mainBundle] pathForResource:@"PListFile" ofType:@"plist"]];
NSLog(@"%@", [[[rootDictionary objectForKey:@"updates"] objectAtIndex:0] objectForKey:@"url"]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-02
    • 1970-01-01
    • 2023-04-03
    • 2017-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多