objective-c - 无法读取 Plist...我做错了什么?

标签 objective-c ios cocos2d-iphone plist

我的资源文件夹中有一个名为“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/

相关文章:

iphone - iOS - 将数组元素的一部分转换为字符串

ios - 2个 View Controller ,每个都有自己的xib,其中一个是另一个的子类?

ios - 从cocos2d应用播放iTunes歌曲预览

iphone - 将数组的属性提取到新数组中

objective-c - 有人可以向我解释为什么我看到的某些代码在函数中嵌入了函数吗?

ios - 使用后台队列从 url 加载图像仍然不够快

ios - 在 Swift 中处理 nil 值

ios - GL_DEPTH_COMPONENT24_OES 的等轴瓦贴图闪烁

iphone - cocos2d 中的自由运行/横向滚动类型游戏

ios - AVCaptureMovieFileOutput NSInvalidArgumentException 没有事件/启用的连接