我的资源文件夹中有一个名为“levelconfig.plist”的 plist,我想从中读取一些内容。
我做了以下事情:
-(NSString *) dataFilePath
{
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [path objectAtIndex:0];
return [documentDirectory stringByAppendingPathComponent:@"levelconfig.plist"];
}
-(void) readPlist{
NSString *filePath = [self dataFilePath];
if([[NSFileManager defaultManager] fileExistsAtPath:filePath]){
NSArray *array = [[NSArray alloc]initWithContentsOfFile:filePath];
NSLog(@"%@",array);
NSLog(@"%@", filePath);
}
}
在 ccTouchesBegan 方法中我调用:
[self readPlist];
我的 plist 包含一个数组,应该正确显示它吗?将关卡数据存储在 .plist 文件中是个好主意吗?
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>sunday</string>
<string>monday</string>
<integer>44</integer>
</array>
</dict>
</plist>
最佳答案
您必须首先阅读 plist 中指定的字典。例如:
NSString *mainPath = [[NSBundle mainBundle] bundlePath];
NSString *itemPositionPlistLocation = [mainPath stringByAppendingPathComponent:@"test.plist"];
NSDictionary * itemPositions = [[NSDictionary alloc] initWithContentsOfFile:itemPositionPlistLocation];
NSArray * items = [itemPositions objectForKey:@"Root"];
NSLog(@"%@", items);
我不确定您对其他代码做了什么,但两行足以加载文件。请原谅变量名称;我很快就根据我当前的项目进行了调整。另外,请确保在 dealloc 或任何适当的地方释放数组和字典。
关于objective-c - 无法读取 Plist...我做错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8371465/