乱数を生成してその数値がすでに使用されているかどうかを確認する代わりに、0から29までの数値(それぞれNSNumberでラップされている)のNSMutableArrayを作成し、このSOでGregoryGoltsovによって提供されるカテゴリを使用して配列をランダムにシャッフルします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
編集
私は最初にクリストファー・ジョンソンの答えを言いましたが、私は本当にグレゴリー・ゴルツォフの答えを意味しました
(Ymiespañolespeor queelInglés)