从plist中读取一系列字典

时间:2013-01-08 15:31:50

标签: nsmutablearray nsarray plist nsdictionary

嗨,我正试图读取plist的值,这就是我的plist看起来像atm

<plist version="1.0">
<array>
    <dict>
        <key>Title</key>
        <string>Mickey Mouse</string>
        <key>Image</key>
        <string>mickeymouse.png</string>
        <key>Hint1</key>
        <string>Hint 1</string>
        <key>Hint2</key>
        <string>Hint 2</string>
        <key>Hint3</key>
        <string>Hint 3</string>
    </dict>
    <dict>
        <key>Title</key>
        <string>Peter Pan</string>
        <key>Image</key>
        <string>peterpan.png</string>
        <key>Hint1</key>
        <string>Hint 1</string>
        <key>Hint2</key>
        <string>Hint 2</string>
        <key>Hint3</key>
        <string>Hint 3</string>
    </dict>
</array>
</plist>

这是我正在使用的代码,但它只是崩溃了。

AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSString *questionNumber = [NSMutableString stringWithFormat:@"Item 0"];
NSString *path = [[NSBundle mainBundle] pathForResource:@"Level1" ofType:@"plist"];
NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:path];
NSDictionary *questionNumberDictionary = [array objectForKey:questionNumber];
NSString *questionTitle = [questionNumberDictionary objectForKey:@"Title"];
NSString *questionImage = [questionNumberDictionary objectForKey:@"Image"];
NSString *questionHint1 = [questionNumberDictionary objectForKey:@"Hint1"];
NSString *questionHint2 = [questionNumberDictionary objectForKey:@"Hint2"];
NSString *questionHint3 = [questionNumberDictionary objectForKey:@"Hint3"];

1 个答案:

答案 0 :(得分:7)

您在以下行中遇到问题

<强> NSDictionary *questionNumberDictionary = [array objectForKey:questionNumber];

而不是你需要使用for循环遍历数组

 NSString *path = [[NSBundle mainBundle] pathForResource:@"Level1" ofType:@"plist"];
    NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:path];

    for (NSDictionary *dict in array) {
        NSString *questionTitle = [dict objectForKey:@"Title"];
        NSString *questionImage = [dict objectForKey:@"Image"];
        NSString *questionHint1 = [dict objectForKey:@"Hint1"];
        NSString *questionHint2 = [dict objectForKey:@"Hint2"];
        NSString *questionHint3 = [dict objectForKey:@"Hint3"];

    }

这将解决您的问题。