dictionaryWithContentsOfFile returning nil from my property list file

好久不见. 提交于 2019-12-08 17:22:50

问题


I'm learning how to use plist files for storing data in my iPhone app. I've been reading a bunch of the questions about plist and dictionaryWithContentsOfFile on this site, but can't see what I'm doing wrong.

The following line returns nil ("The dictionary is null" to the console).

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

The myFile.plist file is in the resources folder, and contains a few strings:

<?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>

Am I missing something here?


回答1:


From the documentation...

+ (id)dictionaryWithContentsOfFile:(NSString *)path

Parameters

path

A full or relative pathname. The file identified by path must contain a string representation of a property list whose root object is a dictionary.

Return Value

A new dictionary that contains the dictionary at path, or nil if there is a file error or if the contents of the file are an invalid representation of a dictionary.

So, you need to probably construct a full path to your plist file (or pass in an appropriate relative path. I'd be very surprised if "myFile" is an appropriate relative path). If you build a proper path but then are still getting nil back, then you've probably got an invalid plist file.

The easiest way to get a path for a file in your resources folder is like this:

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

That will build a path for a file called "myFile.plist" inside your Resources folder.



来源:https://stackoverflow.com/questions/3895898/dictionarywithcontentsoffile-returning-nil-from-my-property-list-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!