代替產生隨機數,並檢查是否該數字已被使用,我將創建的數字一個NSMutableArray 0至29(每個包裹在一個NSNumber),然後隨機洗牌數組使用由Gregory Goltsov在這個SO問題whats-the-best-way-to-shuffle-an-nsmutablearray中提供的類別。
然後,您只需從NSMutable數組的開始遍歷每個NSNumber對象。即
#import "NSMutableArray_Shuffling.h // From Gregory Goltsov
NSMutableArray* randomNumbers = [[NSMutableArray alloc] init];
for(int i=0; i<30; i++) {
[randomNumbers addObject:[NSNumber numberWithInt:i]];
}
[randomNumbers shuffle]; // From Gregory Goltsov
...
int lastIndex = 0;
-(IBAction)randomear
{
if (lastIndex<30) {
NSNumber* theRandomNumber = [randomNumbers objectAtIndex:lastIndex];
int theQuestion = [theRandomNumber intValue];
if (theQuestion == 0) {
labelpregunta.text = @"Las ovejas pueden nadar?";
}
if (theQuestion == 1) {
labelpregunta.text = @"Con que se tiñe la lana de negro?";
}
if (theQuestion == 2) {
labelpregunta.text = @"De que material es el mejor casco?";
}
if (theQuestion == 3){
labelpregunta.text = @"Para fabricar lana necesitas 4 _____";
}
//et cetera/ etcétera
lastIndex++;
} else {
// No more questions
}
}
但是,最好用一系列包含單個問題的問題和答案的對象填充數組。即
@interface aQuestion : NSObject
@property (nonatomic, string) NSString* question;
@property (nonatomic, string) NSString* answer;
-(void)initWithQuestion:(NSString)aQuestion and:(NSString) anAnswer;
-(BOOL)isCorrectAnswer(NSString testAnswer);
@end
@implementation aQuestion
-(void)initWithQuestion:(NSString*)aQuestion and:(NSString*) anAnswer
{
if(!(self=[super init])) return self;
question = aQuestion;
answer = anAnswer;
return self;
}
-(BOOL)isCorrectAnswer(NSString testAnswer)
{
[answer isEqualToString:testAnswer];
}
@end
...
#import "NSMutableArray_Shuffling.h // From Gregory Goltsov
NSMutableArray* questions = [[NSMutableArray alloc] init];
[questions addObject:[[aQuestion alloc] initWithQuestion:@"Question 1" and:@"Answer 1"]];
[questions addObject:[[aQuestion alloc] initWithQuestion:@"Question 2" and:@"Answer 2"]];
[questions addObject:[[aQuestion alloc] initWithQuestion:@"Question 3" and:@"Answer 3"]];
[questions addObject:[[aQuestion alloc] initWithQuestion:@"Question 4" and:@"Answer 4"]];
[questions shuffle]; // From Gregory Goltsov
...
for(int i=0; i<[questions count]; i++) {
aQuestion* theQuestion = [questions objectAtIndex:i];
// Ask theQuestion.question
labelpregunta.text = theQuestion.question;
...
// wait for theAnswer
....
NSString theAnswer = labelrespuesta.text;
if ([theQuestion isCorrectAnswer:theAnswer]) {
// You win!!!!!!!
}
}
// No more questions
編輯
我最初說Kristopher約翰遜的答案,但我真正的意思格雷戈裏Goltsov的回答
(Y英里西班牙語ES珥闕埃爾英語)
什麼「它不需要重複提問」是什麼意思?你的意思是它應該只提出一個問題,或者你的意思是它可以不止一次提出每個問題? – mydogisbox 2012-07-18 18:39:45
我不知道Objective-C,但也許你可以理解的原則:http://jsfiddle.net/tx2Bq/1/ – Mageek 2012-07-18 18:46:40
可能重複的[非重複隨機數字](http://stackoverflow.com/問題/ 1617630/non-repeating-random-numbers) – 2012-07-18 18:48:13