从plist文件</nil>读取时,NSDictionary包含<nil>值

时间:2013-01-01 18:48:11

标签: iphone objective-c ios

我目前正在尝试读取一个plist文件,并尝试在UITableView中显示数据,但在读取plist文件时,我收到了nil数据。

修改

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">
<array>
    <dict>
        <key>Title</key>
        <string>Mr</string>
        <key>First Name</key>
        <string>xxxxxx</string>
        <key>Last Name</key>
        <string>yyyyyyy</string>
        <key>Designation</key>
        <string>Senior Engineer</string>
    </dict>
</array>
</plist>

现在代码

NSString *path = [[NSBundle mainBundle] pathForResource:@"Data" ofType:@"plist"];

NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];

NSArray *valueArray = [dict allKeys];

/*
Printing description of path:
/Users/rock/Library/Application Support/iPhone Simulator/6.0/Applications/2567D2B3-56D4-4464-9EFC-CAB923ABE955/PlistTableView.app/Data.plist
Printing description of dict:
<nil>
Printing description of valueArray:
<nil>
*/

现在字典和数组包含没有数据是什么原因?我怎样才能显示关键和&amp;表视图中的值?

3 个答案:

答案 0 :(得分:2)

你的plist文件包含一个字典 inside 一个数组。所以要么使用

NSArray *array = [[NSArray alloc] initWithContentsOfFile:path];
NSDictionary *dict = [array objectAtIndex:0];

或将plist文件的结构更改为

<plist version="1.0">
<dict>
    <key>Title</key>
    <string>Mr</string>
    <key>First Name</key>
    <string>xxxxxx</string>
    <key>Last Name</key>
    <string>yyyyyyy</string>
    <key>Designation</key>
    <string>Senior Engineer</string>
</dict>
</plist>

答案 1 :(得分:1)

在顶部,您有<array>而不是<dict>。所以应该这样......

NSString *path = [[NSBundle mainBundle] pathForResource:@"Data" ofType:@"plist"];
NSArray *array = [[NSArray alloc] initWithContentsOfFile:path];
NSDictionary *dict=[array objectAtIndex:0];
NSArray *valueArray = [dict allKeys];

答案 2 :(得分:-1)

在文件开头尝试:

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