从plist中选择唯一的随机字典

时间:2011-03-24 16:30:27

标签: iphone random dictionary

我正在开发一个函数,允许我从.plist中选择一个随机字典来播放2个字符串,问题和答案都可以正常工作。但有时会选择相同的字典。随机函数每次都可以显示一个独特的字典吗?感谢。

plist中:

<dict>
<key>questions</key>
<array>
    <dict>
        <key>question</key>
        <string>q1</string>
        <key>answer</key>
        <string>a1</string>
    </dict>
    <dict>
        <key>question</key>
        <string>q2</string>
        <key>answer</key>
        <string>a2</string>
    </dict>
    <dict>
        <key>question</key>
        <string>q3</string>
        <key>answer</key>
        <string>a3</string>
    </dict>
</array>

的.m:

    NSString *path = [[NSBundle mainBundle] pathForResource:@"qs" ofType:@"plist"];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithContentsOfFile:path];

    NSMutableArray *array = [dict objectForKey:@"questions"];

    int questionIndex = arc4random() %[array count];

    NSDictionary *question = [array objectAtIndex:questionIndex];
    NSString *answerStr = [question objectForKey:@"answer"];
    NSString *questionStr = [question objectForKey:@"question"];

    label1.text = answerStr;
    label2.text = questionStr;

1 个答案:

答案 0 :(得分:0)

如果您不想两次显示相同的字典,请执行以下操作:

  • 跟踪您显示的词典。如果您再次选择一个,请再试一次
  • 当您选择字典时,请从选择数组中删除它。