简体   繁体   中英

Select unique random dictionary from plist

I am working on a function that allows me to select a random dictionary from a .plist that dis plays 2 string a question and answer which works fine. However sometimes the same dictionary is selected. Is it possible for the random function to show a unique dictionary each time? Thanks.

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;

If you don't want to show the same dictionary twice, either:

  • keep track of the dictionaries you have shown. If you select one for a second time, try again
  • when you choose a dictionary, remove it from the array of choices.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM