Objective C - Random XIB pick
I have already posted another question about this, but no one seemed to know how to do this.
I want my app to pick a random XIB file for me, but dont use the ones that have already been randomly picked.
So heres what i have set up as of right now, it seems to wor开发者_高级运维k, but i have to keep pressing the button over and over until it finds one that hasnt be used.
-(IBAction)continueAction:(id)sender{
random = arc4random() % 2;
if (random == 0 && usedQ2 == 0) {
Question_2 *Q2 = [[Question_2 alloc] initWithNibName:@"Question 2" bundle:nil];
Q2.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:Q2 animated:YES];
[Q2 release];
}
else if (random == 1 && usedQ3 == 0) {
Question_3 *Q3 = [[Question_3 alloc] initWithNibName:@"Question 3" bundle:nil];
Q3.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:Q3 animated:YES];
[Q3 release];
}
}
So as you can see i have it pick from a random number, and from their find the one that it matches.
Then you can see i have another part of my if statement that is checking to make sure it hasn't been used before.
each NIB file has its own usedQ(whatever Q it is), and when that Nib file is loaded it puts that usedQ as 1.
I think i could get by doing this, but in order to get rid of the constant button pushing, i will have to put loads of else statements with more else statements in them.
I have also tried running the
random = arc4random() % 2;
in a while statement and a for statement, i hoped that it would keep looking for a number until one that hasn't be used was found with no luck.
Any help? thanks!
- Why don't you make a mutable array and populate it with the names of all your nibs.
- Then read the count of the array and generate a random number in that range.
- Extract the nib name at that index and remove it from the array.
- repeat steps 2-3.
//Setup your list at an appropriate place
NSMutableArray *nibs = [[NSMutableArray alloc] initWithObjects: @"One Nib", @"Another Nib", @"Last Nib", nil];
self.unusedNibs = nibs; //This should be a property you declare in your header.
[nibs release];
-(IBAction)continueAction:(id)sender{ int random = arc4random() % [self.unusedNibs count];
NSString *nibName = [self.unusedNibs objectAtIndex: random];
[self.unusedNibs removeObjectAtIndex: random];
//Load nib here. }
精彩评论