Plist Array到NSArray没有对象

时间:2011-11-07 23:37:16

标签: iphone objective-c ios ipad plist

所以我之前已经搜索并阅读并成功完成了这项工作,但是我遇到了这个问题。

我有一个字符串数组的plist。我没有被读入数组的对象。我成功地为另一个控制器中的字典做了这个。所以这是我的代码。

    // Open plist and get brands
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"brands" ofType:@"plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:plistPath]) {
    NSLog(@"The file exists");
} else {
    NSLog(@"The file does not exist");
}

_brands = [NSArray arrayWithContentsOfFile:plistPath];

_catList = [[[NSMutableArray alloc] initWithCapacity:[_brands count]] autorelease];

这是我的plist。请注意,_brands数组被定义为NSArray *品牌,属性设置为非原子,只读并且合成为brands = _brands。

<?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>Brand A</string>
        <string>Brand B</string>
        <string>Brand C</string>
        <string>Brand D</string>
    </array>
</dict>
</plist>

我看到有一个标签,但在Xcode中它显示为带有字符串的数组。不是字典&gt;数组&gt;许多字符串

2 个答案:

答案 0 :(得分:7)

PLists是他们心中的词典(请注意&lt; dict&gt;标记)。将文件读入NSDictionary,然后使用objectforKey:方法和Root密钥向字典询问数组。

NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:plistPath];
_brands = [dict objectForKey:@"Root"];

答案 1 :(得分:3)

NSString *plistPath = [self copyFileToDocumentDirectory:plistFileName];
NSDictionary *plistContents=[[NSDictionary alloc] initWithContentsOfFile:plistPath];

[plistPath release];
return  plistContents;