Objective c NSArray initWithContentsOfFile返回nil
我正试图使用Objective c NSArray initWithContentsOfFile返回nil,objective-c,ios5,xcode4,xcode4.2,Objective C,Ios5,Xcode4,Xcode4.2,我正试图使用initWithContentsOfFile将plist文件读入NSArray 我的代码如下所示 NSBundle *bundle = [NSBundle mainBundle]; NSString *plistPath = [bundle pathForResource: @"routes" ofType:@"plist" ]; routes = [[NSArray alloc] initWithCont
initWithContentsOfFile
将plist文件读入NSArray
我的代码如下所示
NSBundle *bundle = [NSBundle mainBundle];
NSString *plistPath = [bundle pathForResource:
@"routes" ofType:@"plist" ];
routes = [[NSArray alloc] initWithContentsOfFile:plistPath ];
NSLog:(@"contents of myArray %@", routes);
routes.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>Root</key>
<array>
<string>1</string>
<string>2</string>
</array>
</dict>
</plist>
根
1.
2.
一切似乎都很好plistPath
使用正确的值初始化,这意味着文件被复制到捆绑包中并可以读取。但是routes=[[NSArray alloc]initWithContentsOfFile:plistPath]代码>返回0x0
值。我认为这等于nil
我的代码怎么了?实际上你的plist是一本字典
更改此项:
<dict>
<key>Root</key>
<array>
<string>1</string>
<string>2</string>
</array>
</dict>
根
1.
2.
为此:
<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"];
伙计,你说得对。但在Xcode可视化编辑器中,我选择了数组类型!查看我添加的屏幕截图。是Xcode4错误吗?不是。您有一个数组对象,其键名为“Root”(表示您的plist是一个“NSDictionary
”)。您可以在该级别添加具有不同键名的其他对象。但别无选择,Xcode默认创建dict,您无法在visual editor中更改它。仅通过将plist作为源文件进行编辑。但现在我知道了。谢谢是的,如果需要根数组,就必须在XML中正确执行。