Plist cannot be read … What am I doing wrong?

馋奶兔 提交于 2019-12-11 14:47:29

问题


I have got a plist in my Resources folder called "levelconfig.plist" and I want to read something out of it.

I did the following :

-(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);

    }


}

And in the ccTouchesBegan method I call :

[self readPlist];

My plist contains an array, that should be displayed right ? Is it a good idea to store level data in a .plist file ?

plist file:

<?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>

回答1:


You must first read the dictionary as specified in your plist. For example:

NSString *mainPath = [[NSBundle mainBundle] bundlePath];
NSString *itemPositionPlistLocation = [mainPath stringByAppendingPathComponent:@"test.plist"];
NSDictionary * itemPositions = [[NSDictionary alloc] initWithContentsOfFile:itemPositionPlistLocation];
NSArray * items = [itemPositions objectForKey:@"Root"];
NSLog(@"%@", items);

I'm not sure what you are doing with your other code but two lines suffice to load the file. Please excuse the variable names; I quickly adapted this from my current project. Also, make sure you release the Array and Dictionary in dealloc or wherever appropriate.




回答2:


Are you sure it's in your resources folder? In that case you aren't building the path properly. You will probably want to use [NSBundle pathForResource:] (docs)




回答3:


Your pList file is a Dictionary that has an array in the Root key and you are reading it in to an Array.

-(void) readPlist{
        NSString *filePath = [self dataFilePath];
    if([[NSFileManager defaultManager] fileExistsAtPath:filePath]){
        NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:filePath];
        NSArray *array = [[NSArray alloc]initWithArray:[dict objectForKey:@"Root"]];
        NSLog(@"%@",array);
        NSLog(@"%@", filePath);
        [dict release];
        [array release];

    }
}


来源:https://stackoverflow.com/questions/8371465/plist-cannot-be-read-what-am-i-doing-wrong

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!