NSArray initWithContentsOfFile返回nil

时间:2012-06-03 21:59:16

标签: objective-c ios5 xcode4 xcode4.2

我正在尝试使用NSArray阅读plist文件initWithContentsOfFile,如here所述

我的代码看起来像这样

    NSBundle *bundle = [NSBundle mainBundle];
    NSString *plistPath = [bundle pathForResource:
                           @"routes" ofType:@"plist" ];
    routes = [[NSArray alloc] initWithContentsOfFile:plistPath ];
    NSLog:(@"contents of myArray %@", routes);

routes.plist具有非常简单的数组结构和

中的2个字符串值
<?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>Root</key>
    <array>
        <string>1</string>
        <string>2</string>
    </array>
</dict>
</plist>

This is how it looks in xcode

一切似乎都很好。 plistPath使用正确的值进行初始化,这意味着文件被复制到包中并且可以被重新加载。但是routes = [[NSArray alloc] initWithContentsOfFile:plistPath ];会返回0x0值。我认为这等于nil

我的代码出了什么问题?

2 个答案:

答案 0 :(得分:8)

实际上你的plist是一本字典。

改变这个:

<dict>
    <key>Root</key>
    <array>
        <string>1</string>
        <string>2</string>
    </array>
</dict>

到此:

<array>
    <string>1</string>
    <string>2</string>
</array>

答案 1 :(得分:2)

我想你想做这样的事情:

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

NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfFile:plistPath];
NSArray *routes = [dictionary objectForKey:@"Root"];