Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Anyone know how to randomize questions in a quiz game?

Hi everyone I'm currently trying to make a quiz game app for the iphone after learning the basics. I was wondering how do you put questions in a random order so each time you start the game a different question shows up? Thanks.

1 Answer

Store the questions in an array:

NSArray* questions = @[@"Question 1", @"Question 2", @"Question 3"];

Generate a random number:

NSInteger randomInteger = arc4random_uniform(questions.count);

Access a random question:

NSString* randomQuestion = questions[randomInteger];

Thanks, but doesn't that only show the questions? I guess to be more clear in my question. I'm trying to basically randomize view controllers cuz each of them is a question. Does the concept go the same for that?

NSArray* arrayOfViewControllerClasses = @[[SomeViewController0 class], [SomeViewController1 class], [SomeViewController2 class]];

NSInteger randomInteger = arc4random_uniform(arrayOfViewControllerClasses.count);

UIViewController* viewController = [[arrayOfViewControllerClasses[randomInteger] alloc] init];

Thanks so much. I'll try that.

How do I connect a button for the randomize code to work?