我想制作一个问题应用程序,它显示了我制作的一个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 :(得分:2)
rand()%7;
将始终生成一个独特的随机数序列。
改为使用arc4random() % 7;
。
currentQuestion=arc4random() %7;
答案 1 :(得分: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;
}
答案 2 :(得分:1)