对app bundle中plist的访问返回null

Ron*_*onC 12 objective-c plist nsbundle ios

我正在使用我之前使用的一段代码成功将plist加载到数组中:

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"species_names" ofType:@"plist"];
NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
Run Code Online (Sandbox Code Playgroud)

initWithContentsOf文件失败(数组为null,表明它无法在应用程序包中找到plist).

在iPhone模拟器下我检查了第一行创建的路径指向app文件(确实如此),并使用Finder上下文菜单"Show package contants"向自己证明"species_name.plist"实际上是捆绑 - 一个长度表明它包含东西,所以它应该工作(并在我写的其他iOS应用程序中).建议最受欢迎......

[env Xcode 4.2 beta,iOS 4.3.2].

Ven*_*MKO 27

你应该使用实例的initWithContentsOfFile:方法NSDictionary,而不是NSArray.这是样本:

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"species_names" ofType:@"plist"];
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:filePath];
NSArray *array = [NSArray arrayWithArray:[dict objectForKey:@"Root"]];
Run Code Online (Sandbox Code Playgroud)

或这个:

NSString *errorDesc = nil;
NSPropertyListFormat format;
NSString    *path = [[NSBundle mainBundle] pathForResource:@"startups" ofType:@"plist"];
NSData      *plistXML = [[NSFileManager defaultManager] contentsAtPath:path];
NSDictionary *temp = (NSDictionary *)[NSPropertyListSerialization                     
                                          propertyListFromData:plistXML
mutabilityOption:NSPropertyListMutableContainersAndLeaves
                                          format:&format
                                          errorDescription:&errorDesc];
NSArray *array = [NSArray arrayWithArray:[temp objectForKey:@"Root"]];
Run Code Online (Sandbox Code Playgroud)


编辑

你可以使用用initWithContentsOfFile:方法NSArray创建的文件的writeToFile:atomically:方法NSArray.创建的Plist writeToFile:atomically:具有以下结构:

<plist version="1.0">
<array>
    ...Content...
</array>
</plist>
Run Code Online (Sandbox Code Playgroud)

在XCode中创建的Plist有这样的结构:

<plist version="1.0">
<dict>
    ...Content...
</dict>
</plist>
Run Code Online (Sandbox Code Playgroud)

这就是为什么dosnt的initWithContentsOfFile:方法NSArray有效.