2012-11-15 69 views
3

我想提出一個問題應用程序,它顯示了我製作的plist中的一個隨機問題。這是功能(目前只有7個問題)。不重複的問題應用程序

我的功能給出了一個隨機問題,但它總是以相同的問題 開頭,可以重複一個問題。我需要你的幫助來隨機生成問題,而不會重複。

currentQuestion=rand()%7; 
NSDictionary *nextQuestion = [self.questions objectAtIndex:currentQuestion]; 

    self.answer = [nextQuestion objectForKey:@"questionAnswer"]; 

    self.qlabel.text = [nextQuestion objectForKey:@"questionTitle"]; 

    self.lanswer1.text = [nextQuestion objectForKey:@"A"]; 

    self.lanswer2.text = [nextQuestion objectForKey:@"B"]; 

    self.lanswer3.text = [nextQuestion objectForKey:@"C"]; 

    self.lanswer4.text = [nextQuestion objectForKey:@"D"]; 
+0

嘿Eyasin,我沒有得到你,你爲什麼要我來編輯代碼? – MANN

回答

2

rand()%7;將始終產生一個唯一的隨機數序列。

改爲使用arc4random() % 7;

currentQuestion=arc4random() %7; 
1
  1. 使用你的問題鍵的數組。假設你有一個名稱爲arrKeys的數組 - > [A],[B],[C],[D],...,[z],無
  2. 使用(arc4random()%array.length-1){如Suresh所建議}爲您的陣列生成rendom索引。假設你得到rand = 3
  3. 從數組arrKeys @ 3 = D獲取密鑰。然後從你的NSDictionary使用[nextQuestion objectForKey:@「D」],並從數組中刪除'D'鍵作爲[arrKeys removeObjectAtIndex: 3]。爲下一個問題重複1-3步。
+0

suresh:thnx 4回放你的幫助me.with序列的東西,但仍然不是唯一的數字 – eyasin

+0

曼:我沒有太多的經驗,在目標c可以幫助寫代碼你解釋 – eyasin

+0

參考@ danh的答案如下。這就是你正在尋找的。 –

2

我會做這種方式(在ARC,寫出超長爲清楚起見):

@property (nonatomic,strong) NSDictionary *unaskedQuestions; 

- (NSString *)nextRandomUnaskedQuestion { 

    if (!self.unaskedQuestions) { 
     // using your var name 'nextQuestion'. consider renaming it to 'questions' 
     self.unaskedQuestions = [nextQuestion mutableCopy]; 
    } 

    if ([self.unaskedQuestions count] == 0) return nil; // we asked everything 

    NSArray *keys = [self.unaskedQuestions allKeys]; 
    NSInteger randomIndex = arc4random() % [allKeys count]; 
    NSString *randomKey = [keys objectAtIndex:randomIndex]; 
    NSString *nextRandomUnaskedQuestion = [self.unaskedQuestions valueForKey:randomKey]; 

    [self.unaskedQuestions removeObjectForKey:randomKey]; 
    return nextRandomUnaskedQuestion; 
}