Read iOS Programming: The Big Nerd Ranch Guide, 3/e (Big Nerd Ranch Guides) Online

Authors: Aaron Hillegass,Joe Conway

Tags: #COM051370, #Big Nerd Ranch Guides, #iPhone / iPad Programming

iOS Programming: The Big Nerd Ranch Guide, 3/e (Big Nerd Ranch Guides) (7 page)

Implementing Methods

Methods and instance variables are declared in the header file (in this case,
QuizViewController.h
), but the actual code for the methods is placed in the implementation file (in this case,
QuizViewController.m
). Select
QuizViewController.m
in the project navigator.

 

When you create a new application in
Xcode
, the template fills in a lot of boiler-plate code. This code may be useful for you later on, but for now, it is distracting. So we’re going to remove it. In
QuizViewController.m
, delete everything between the
@implementation
and
@end
directives so that
QuizViewController.m
looks like this:

 
@implementation QuizViewController
@end
 

When the application launches, the
QuizViewController
will be sent the message
initWithNibName:bundle:
. In
QuizViewController.m
, implement the
initWithNibName:bundle:
method by adding the following code that creates two arrays and fills them with questions and answers.

 
@implementation QuizViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    // Call the init method implemented by the superclass
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    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;
}
@end

As you work through this book, you will type a lot of code. Notice that as you were typing this code,
Xcode
was ready to fill in parts of it for you. For example, when you started typing
initWithNibName:bundle:
, it suggested this method before you could finish. You can hit the Return key to accept
Xcode
’s suggestion or select another suggestion from the pop-up box that appears.

 

However, there are two things to watch out for when using code-completion. First, when you accept a code-completion suggestion for a method that takes arguments,
Xcode
puts
placeholders
in the areas for the arguments.

 

Placeholders are not valid code, and you have to replace them to build the application. This can be confusing because placeholders often have the same names that you want your arguments to have. So the text of the code looks completely correct, but you get an error.

 

Figure 1.19
shows two placeholders you might have seen when typing in the previous code.

 

Figure 1.19  Example of code-completion placeholder and errors

 

See the
nibNameOrNil
and
nibBundleOrNil
in the first line of the implementation of
initWithNibName:bundle:
? Those are placeholders. You can tell because they are inside slightly-shaded, rounded rectangles. The fix is to delete the placeholders and type in arguments of your own (with the same names). The rounded rectangles will go away, and your code will be correct and valid.

 

Second, don’t blindly accept the first suggestion
Xcode
gives you without verifying it. Cocoa Touch uses naming conventions, which often cause distinct methods, types, and variables to have very similar names. Many times, the code-completion will suggestion something that looks an awful lot like what you want, but it is not the code you are looking for. Always double-check.

 

Now back to your code. In the declarations in
QuizViewController.h
, neither
questions
or
answers
is labeled
IBOutlet
. This is because the objects that
questions
and
answers
point to are created and configured programmatically in the code above instead of in the XIB file. This is a standard practice: view objects are typically created in XIB files, and model objects are always created programmatically.

 

In addition to the
initWithNibName:bundle:
method, we need two action methods for when the buttons are tapped. In
QuizViewController.m
, add the following code after the implementation of
initWithNibName:bundle:
. Make sure this code is before the
@end
directive but not inside the curly brackets of the
initWithNibName:bundle:
implementation.

 
    ...
    // Return the address of the new object
    return self;
}
- (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];
}
@end
 

Flip back to
Figure 1.12
. This diagram should make a bit more sense now that you have all of the objects and the connections shown.

 
Build and Run on the Simulator

Now you are ready to build the application and run it on the simulator. You can click the
iTunes
-esque play button in the top left corner of the workspace, but you’ll be doing this often enough that it’s easier to remember and use the keyboard shortcut Command-R. Either way, make sure that the
Simulator
option is selected in the pop-up menu next to the play button (
Figure 1.20
).

 

Figure 1.20  Running the application

 

If there are any errors or warnings, you can view them in the
issue navigator
by selecting the
icon in the navigator selector (
Figure 1.21
). The keyboard shortcut for the issue navigator is Command-4. In fact, the shortcut for any navigator is Command plus the navigator’s position in the selector. For example, the project navigator is Command-1.

 

Figure 1.21  Issue navigator with errors and warnings

 

You can click on any issue in the issue navigator, and it will take you to the source file and the line of code where the issue occurred. Find and fix any issues you have (i.e., code typos!) by comparing your code with the book’s and then build the application again. Repeat this process until your application compiles.

 

Once your application has compiled, it will launch in the iOS simulator. But before you play with it, you’ll want the console visible so that you can see the output of the log statements. To see the console, reveal the
debug area
by clicking the middle button in the
group at the top right of the workspace window.

 

The console is on the righthand side of the debug area, and the variables view is on the left. You can toggle these panels with the
control in the top-right corner of the debug area
Figure 1.22
. You can also resize the debug area and its panels by dragging their frames. (In fact, you can resize any area in the workspace window this way.)

 

Figure 1.22  Debug area expanded

 

Play around with the
Quiz
application. You should be able to tap the
Show Question
button and see a new question in the top label; tapping
Show Answer
should show the right answer. If your application isn’t working as expected, double-check your connections in
QuizViewController.xib
and check the console output when you tap the buttons.

 

Other books

Wolf Hunt by Armand Cabasson, Isabel Reid (Translator)
Obfuscate by Killion Slade
Fallen by Quiana
Maxwell's Island by M.J. Trow
Las niñas perdidas by Cristina Fallarás
Just Another Job by Casey Peterson
Dance by Kostova, Teodora
Winter Winds by Gayle Roper


readsbookonline.com Copyright 2016 - 2024