I am trying to make a random quiz app for the iPhone. I don't know about how to do that. There will be several questions, and I don't want to build a separate view for each one. What format I should import the questions in to the app, and then set it up to do questions in random order, and by category?
There are lots of ways to handle this. Here's one:
Create a dictionary object that has keys for the question, each possible answer, and the index of the correct answer (I'd make the list of possible answers an array inside the dictionary.)
Create an array of these dictionary objects. Each dictionary will be a quiz question and it's answers. The array will be an array of all possible quiz questions.
Save the array to a plist in your application bundle.
At launch, use NSArray arrayWithContentsOfFile to read the contents of your plist into an array of all your questions. Let's call that instance variable allQuizQuestions.
At the beginning of a quiz run, copy all the quiz question objects into a mutable array:
Code:
NSMutableArray *currentQuizQuestions =
[allQuizQuestions mutableCopy];
Then when you want to ask a question, get a random index into your current array of questions, fetch that question, and delete it from the array:
Code:
- (NSDictionary *) getRandomQuestion;
{
int count = [currentQuizQuestions count];
if (!count)
return nil;
int randomIndex = arc4random_uniform(count);
NSDictionary *aQuestion = [currentQuizQuestions objectAtIndex: randomIndex];
[currentQuizQuestions removeObjectAtIndex: randomIndex];
return aQuestion;
}