2011-03-24 53 views
0

我正在研究一個函數,該函數允許我從.plist中選擇一個隨機詞典,它可以播放2個字符串,這個問題和答案可以正常工作。但是有時選擇相同的字典。隨機函數可能每次都顯示一個唯一的字典嗎?謝謝。從plist中選擇獨特的隨機詞典

的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; 

回答

0

如果你不想表現出同樣的字典兩次,或者:

  • 跟蹤你已經顯示的字典。如果您再次選擇一個,請在您選擇字典時再次嘗試
  • ,將其從選項陣列中刪除。
+0

你會碰巧知道我嘗試removeLastObject的語法:數組和RemoveObjectAtIndex:questionIndex但他們沒有工作 – waqqas 2011-03-24 17:10:19