【问题标题】:dictionaryWithContentsOfFile returning nil from my property list filedictionaryWithContentsOfFile 从我的属性列表文件返回 nil
【发布时间】:2011-04-23 04:38:08
【问题描述】:

我正在学习如何使用 plist 文件在我的 iPhone 应用程序中存储数据。我一直在这个网站上阅读一堆关于 plist 和 dictionaryWithContentsOfFile 的问题,但看不出我做错了什么。

以下行返回 nil(“字典为空”到控制台)。

NSLog(@"The dictionary is %@",[NSDictionary dictionaryWithContentsOfFile:@"myFile"]);

myFile.plist 文件位于资源文件夹中,包含一些字符串:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>name</key>
    <string>john</string>
    <key>aname</key>
    <string>jen</string>
</dict>
</plist>

我错过了什么吗?

【问题讨论】:

    标签: iphone objective-c properties plist nsdictionary


    【解决方案1】:

    来自文档...

    + (id)dictionaryWithContentsOfFile:(NSString *)path

    参数

    路径

    完整或相对路径名。由路径标识的文件必须包含一个属性列表的字符串表示形式,其根对象是一个字典。

    返回值

    在路径中包含字典的新字典,如果存在文件错误或文件内容是字典的无效表示,则为 nil。

    因此,您可能需要构建 plist 文件的完整路径(或传入适当的相对路径。如果“myFile”是适当的相对路径,我会感到非常惊讶)。如果你建立了一个正确的路径,但仍然得到nil,那么你可能得到了一个无效的 plist 文件。

    在资源文件夹中获取文件路径的最简单方法如下:

    NSString * plistPath = [[NSBundle mainBundle] pathForResource:@"myFile" ofType:@"plist"];
    

    这将为您的资源文件夹中名为“myFile.plist”的文件构建一个路径。

    【讨论】:

    • +1 用于 mainBundle 方法。当人们试图找到他们的捆绑路径(当然没有[NSBundle mainBunde])并构建自己的资源路径时,我的眼睛很痛......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-13
    • 2019-02-04
    相关资源
    最近更新 更多