I am having a problem making a IBAction that calls each case once in a random order.
I have done a lot of searching and not find a good solution to go about this problem. The code I have so far is-(IBAction) random {
int text = rand() % 5;
switch (text) {
case 0:
textview.text = @"1";
break;
case 1:
textview.text = @"2";
break;
case 2:
textview.text = @"3";
break;
case 3:
textview.text = @"4";
break;
case 4:
textview.text = @"5";
break;
default:
break; 开发者_JAVA百科
}
}
It works fine, but like I said, I only want it to call each case once.
Any help would be greatly appreciated.Since you are trying to set a random text, I'd do it like this:
Add an iVar called something like stringsArray and initialize it on your init:
...
stringsArray = [[NSMutableArray alloc] initWithObjects:@"1", @"2", @"3", @"4", @"5", nil];
...
Your IBAction would look like this:
-(IBAction) random {
if([stringsArray count] == 0) return;
int text = rand() % [stringsArray count];
[textView setText:[stringsArray objectAtIndex:text];
[stringsArray removeObjectAtIndex:text];
}
What about putting the options, as NSNumber
s, in an NSMutableArray
, selecting a random index, display it, and remove it from the array...with some other response if the count reaches zero.
Use srand instead of rand function
Or Better still use
int text = arc4random() % 5;
Well, one way or another you need to keep a "scorecard" and skip options that have already been selected. The scorecard can be a bit map (eg, a simple integer where you set bits), an array of booleans, a list of previously chosen numbers, etc.
The most straight-forward way to code it is to have the body of your logic above in an UNTIL loop and check in the loop, after picking the random number, to see if it's already chosen. If so, iterate in the loop, otherwise set your response, fill in the appropriate "checkmark" in your scorecard, and LEAVE the loop.
But BEWARE: The loop must also include a check to see if all options have already been chosen, and exit with some appropriate indication in that case.
精彩评论