【问题标题】:Plist Array to NSArray no objectsPlist Array 到 NSArray 没有对象
【发布时间】:2011-11-07 23:37:15
【问题描述】:

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

我有一个 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];

这是我的清单。请注意,_brands 数组定义为 NSArray *brands,属性设置为非原子、只读,并合成为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 中它显示为一个带有字符串的数组。不是字典>数组>很多字符串

【问题讨论】:

    标签: iphone objective-c ios ipad plist


    【解决方案1】:

    PL 列表本质上是字典(注意 标签)。将文件读入 NSDictionary,然后使用objectforKey: 方法和Root 键向字典查询数组。

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

    【讨论】:

    • 谢谢!我打算继续将其设置为字典,但我一直在寻找将 plist 直接读入数组的旧教程和示例。旧 iOS 版本是否允许这样做?
    • 我不知道它是否被允许。我一直把它们读到字典里。
    • 我遇到过很多这样的例子:iphonedevelopertips.com/data-file-management/…
    【解决方案2】:
    NSString *plistPath = [self copyFileToDocumentDirectory:plistFileName];
    NSDictionary *plistContents=[[NSDictionary alloc] initWithContentsOfFile:plistPath];
    
    [plistPath release];
    return  plistContents;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多