Iphone 不重复的问题
我想做一个问题应用程序,显示一个随机的问题,从一个plist我。这是函数(现在只有7个问题) 我的函数给出了一个随机问题,但它总是从同一个问题开始 一个问题可以重复。我需要你的帮助,随机生成问题,不要重复Iphone 不重复的问题,iphone,objective-c,Iphone,Objective C,我想做一个问题应用程序,显示一个随机的问题,从一个plist我。这是函数(现在只有7个问题) 我的函数给出了一个随机问题,但它总是从同一个问题开始 一个问题可以重复。我需要你的帮助,随机生成问题,不要重复 currentQuestion=rand()%7; NSDictionary *nextQuestion = [self.questions objectAtIndex:currentQuestion]; self.answer = [nextQuestion objectFor
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"];
rand()%7代码>将始终生成唯一的随机数序列
使用arc4random()%7代码>取而代之
currentQuestion=arc4random() %7;
使用您的问题密钥数组。假设您有一个名为arrKeys的数组-->[A]、[B]、[C]、[D]、,[z] ,零
使用(arc4random()%array.length-1){根据Suresh的建议}为数组生成rendom索引。假设你得到了rand=3
从数组arrKeys@3=D获取密钥。然后从NSDictionary使用[nextQuestion objectForKey:@“D”],并从数组中删除“D”密钥,如[arrKeys removeObjectAtIndex:3]。对下一个问题重复1-3个步骤
我会这样做(在弧中,为了清晰起见写得很长):
suresh:thnx 4回放你帮了我。关于序列的事情,但仍然不是唯一的数字。Mann:我在目标c方面没有太多经验。你能帮我写代码吗?你解释一下下面的答案。这就是你要找的。嘿,埃辛,我没抓到你,你为什么要我编辑你的代码?
@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;
}