Methods and instance variables are declared in the header file (in this case, QuizAppDelegate.h), but the actual code for the methods is placed in the implementation file (in this case, QuizAppDelegate.m). Select QuizAppDelegate.m from the project navigator and type in the following init method. This method creates two arrays and fills them with questions and answers.
@implementation QuizAppDelegate - (id)init { // Call the init method implemented by the superclass self = [super init]; if(self) { // Create two arrays and make the pointers point to them questions = [[NSMutableArray alloc] init]; answers = [[NSMutableArray alloc] init]; // Add questions and answers to the arrays [questions addObject:@"What is 7 + 7?"]; [answers addObject:@"14"]; [questions addObject:@"What is the capital of Vermont?"]; [answers addObject:@"Montpelier"]; [questions addObject:@"From what is cognac made?"]; [answers addObject:@"Grapes"]; } // Return the address of the new object return self; }
In the declarations in QuizAppDelegate.h, neither questions or answers is labeled IBOutlet. The objects that questions and answers point to are created and configured programmatically in the code above instead of by the XIB file.
After the init method, add the two action methods.
- (IBAction)showQuestion:(id)sender { // Step to the next question currentQuestionIndex++; // Am I past the last question? if (currentQuestionIndex == [questions count]) { // Go back to the first question currentQuestionIndex = 0; } // Get the string at that index in the questions array NSString *question = [questions objectAtIndex:currentQuestionIndex]; // Log the string to the console NSLog(@"displaying question: %@", question); // Display the string in the question field [questionField setText:question]; // Clear the answer field [answerField setText:@"???"]; } - (IBAction)showAnswer:(id)sender { // What is the answer to the current question? NSString *answer = [answers objectAtIndex:currentQuestionIndex]; // Display it in the answer field [answerField setText:answer]; }
You will use the default implementations for the rest of the methods, so leave them alone.
Flip back to Figure 1.13. This diagram should make a bit more sense now that you have created all of the objects and connected them in the XIB file.
18.116.36.194