To demonstrate this feature, we will make further amendments to the HelloWorld project we've been working on. Let's suppose we want a way of testing if our Person object is old enough to vote (in the USA, that's 18). To do this, we'll add a method called "oldEnoughToVote". Add the following method prototype to the interface of the Person class (right below -(void) setWeight...):
-(void) oldEnoughToVote;
Next we need to write the code for this method in Person's implementation. Insert the following lines of code in between @implementation and @end.
1 -(void) oldEnoughToVote{
2 if(age>=18){
3 NSLog(@"I am old enough to vote!\n");
4 }
5 else {
6 NSLog(@"I am NOT old enough to vote!\n");
7 }
8 }
Line 1 is the name of the method.
Line 2 is a conditional statement. It only executes the code in Line 3 if the condition between the parentheses is true. In this case, the condition is that the person's age needs to be greater than or equal to 18.
Line 3 is a print statement to the console.
Line 5 is an "else" statement, which the program jumps to if the condition in Line 3 is not met.
Line 6 is an alternative print statement to the console.
We're almost done! Now lets test this method in our main program. Insert the following lines of code in the "main" routine. You can go ahead and delete any other code that's between the brackets from previous lessons. Your new main routine should look like this:
1 int main (int argc, const char * argv[]) {
2 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
3
4 Person * junior;
5 junior = [Person alloc];
6 junior = [junior init];
7
8 [junior setAge:16];
9 [junior oldEnoughToVote];
10 [junior setAge:23];
11 [junior oldEnoughToVote];
12
13 [junior release];
14 [pool drain];
15 return 0;
16 }
Line 8 sets junior's age at 16. Line 9 tests if he's old enough to vote, and prints the answer to the console.
Line 10 changes junior's age to 23. Line 11 tests again and prints the answer to the console.
Click build and run at the top of your Xcode window to see this program in action! Make sure your console window is open, you can click 'Console' under the 'Run' menu at the top of the screen, or press SHIFT-COMMAND-R.
As you can see, when the oldEnoughToVote is called the first time, junior is only 16 and the program informs the user that he cannot vote. When we change his age to 23, the program retests and prints a different statement.
Stay tuned for more lessons on control flow. I think we'll do loops next time...