我不会生成一个随机数并检查该数字是否已被使用,而是创建一个数字 0 到 29 的 NSMutableArray(每个都包含在一个 NSNumber 中),然后使用 Gregory Goltsov 在此 SO 中提供的类别随机打乱数组质疑什么是最好的方式来洗牌一个 nsmutablearray。
然后,您只需从 NSMutable 数组的开头迭代每个 NSNumber 对象。IE
#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
}
}
但是,最好用一系列对象填充数组,这些对象既包含问题又包含单个问题的答案。IE
@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 Johnson 的回答,但我的意思是 Gregory Goltsov 的回答
(Y mi español es peor que el Inglés)