【问题标题】:NSArray initWithContentsOfFile returns nilNSArray initWithContentsOfFile 返回 nil
【发布时间】:2012-06-03 21:59:16
【问题描述】:

我正在尝试使用initWithContentsOfFile 将plist 文件读入NSArray,如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>

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

我的代码有什么问题?

【问题讨论】:

    标签: objective-c ios5 xcode4 xcode4.2


    【解决方案1】:

    其实你的 plist 就是一本字典。

    改变这个:

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

    到这里:

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

    【讨论】:

    • 伙计,你是对的。但在 Xcode 可视化编辑器中,我选择了数组类型!请参阅我添加的屏幕截图。是 Xcode4 的错误吗?
    • 不。您有一个数组对象,其键名为“Root”(这表明您的 plist 是“NSDictionary”)。您可以在该级别添加具有不同键名的其他对象。
    • 但是没有选择,Xcode默认创建dict,你不能在可视化编辑器中改变它。只能通过编辑 plist 作为源文件。但是好吧,现在我知道了。谢谢!
    • 是的,如果你想要一个根数组,你必须在 XML 中做。
    【解决方案2】:

    我想你想做这样的事情:

    NSBundle *bundle = [NSBundle mainBundle];
    NSString *plistPath = [bundle pathForResource:
                           @"routes" ofType:@"plist"];
    
    NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfFile:plistPath];
    NSArray *routes = [dictionary objectForKey:@"Root"];
    

    【讨论】:

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