0

嗨,我正在尝试从 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"];
4

1 回答 1

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"];

    }

这将解决您的问题。

于 2013-01-08T15:42:18.680 回答