Accessing Plist Arrays / Nodes - Objective C [duplicate]

萝らか妹 提交于 2020-01-05 07:22:49

问题


I have a Property List file that I'm using to store questions and answer data. Within this file I have a collection of arrays, within these I store the different categories and questions. However I can't seem to access this data?

The property 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>Category1</key>
<array>
    <array>
        <string>Question1</string>
        <string>Answer1</string>
    </array>
    <array>
        <string>Question2</string>
        <string>Answer2</string>
    </array>
    <array>
        <string>Question3</string>
        <string>Answer3</string>
    </array>
    <array>
        <string>Question4</string>
        <string>Answer4</string>
    </array>
</array>
</dict>
</plist>

Below I'm using to access the property list file by stepping through it using two simple buttons;

-(IBAction)nextleft {
    [self bingsound];
    if (questionCounter > 1) {
        questionCounter -= 1;
    }
    [self nextQuestion];
}

-(IBAction)nextright {
    [self bingsound];
     if (questionCounter < 20) {
         questionCounter += 1;
     }
     [self nextQuestion];
}

-(void)nextQuestion {
    NSArray *pair;
    pair = [categories objectAtIndex:questionCounter];
    plistQuestion = [pair objectAtIndex:0];
    plistAnswer = [pair objectAtIndex:1];
    abbreviation.text = plistQuestion;
}

I'm populating the the category array as follows;

categories = [NSArray arrayWithContentsOfFile:@"questions.plist"];

回答1:


Your property list has a dictionary as the root object, not an array.

Remove these lines from the top:

<dict>
<key>Category1</key>

And this line from the end:

</dict>

Also, follow @murat's advice and derive a correct path to your file instead of a plain string.

In general with issues like this, the debugger is your friend. Put a breakpoint in your method and check at each stage (deriving the path, extracting the array) what values you are getting out.




回答2:


You should provide arrayWithContentsOfFile: with the full path to the plist file. The following should work:

NSString* filePath = [[NSBundle mainBundle] pathForResource:@"questions" ofType:@"plist"];
categories = [NSArray arrayWithContentsOfFile:filePath];


来源:https://stackoverflow.com/questions/12098237/accessing-plist-arrays-nodes-objective-c

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