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

3 回答 3

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;
}
于 2012-11-15T16:03:31.037 回答
2

rand()%7;将始终产生唯一的随机数序列。

改为使用arc4random() % 7;

currentQuestion=arc4random() %7;
于 2012-11-15T14:31:14.080 回答
1
  1. 使用您的问题键数组。假设您有一个名为 arrKeys 的数组 --> [A], [B], [C], [D], ... , [z], nil
  2. 使用 (arc4random() % array.length-1) {asSuggested by Suresh} 为您的数组生成随机索引。假设你有 rand = 3
  3. 从数组 arrKeys @3 = D 中获取键。然后从您的 NSDictionary 中使用 [nextQuestion objectForKey:@"D"] 并从数组中删除“D”键作为 [arrKeys removeObjectAtIndex:3]。对下一个问题重复 1-3 步。
于 2012-11-15T14:44:08.360 回答