Skip to content

Greetings: Add Simple Code


Coding

First we want to focus on making the application work and postpone the polishing on a later page. What we have to do is to implement the methods the UI aka Buttons is calling and react appropriately which means we need to implement the:

  • clearAll
  • greetMe

methods in the code file of the View Controller called: iGreetingsViewContoller.m (please note the .m extension). Anywhere between the @implementation and the @end line we can add the methods. Some methods were already provided by the template even though some of them are commented out. This is the code fro the greetMe method:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@implementation iGreetingsViewController
 
- (void) greetMe: (id) sender {
        NSLog( @"greetMe() called" );
        NSString* greetings = greetInput.text; 
        NSString* theGreeting = [[NSString alloc] initWithFormat: @"%@ Earthlings", greetings]; 
        greetLabel.text = theGreeting; 
        [theGreeting release]; 
} 
 
- (void) clearAll: (id) sender { 
        NSLog( @"clearAll() called" );
        greetInput.text = @""; 
        greetLabel.text = @""; 
}

This is the rundown of the statements in greetMe() method (number indicates line number):

  • 4: prints out a logging statement shown in the console (making sure the method is getting called)
  • 5: reads out the value from the Input Field where we entered the Greetings
  • 6: build the output text by creating a string with a placeholder (%@) which is replaced by the entered greetings
  • 7: set the greeting on the output label’s text property
  • 8: release the String to avoid a memory leak

And now for the clearAll() method:

  • 12: logging statement so that we know if that method is called
  • 13 / 14: sets the text property to an empty string to clear its value Now click on the Build and Go icon and see what our application is doing. It should look like this:

image:iGreetings.first.coding.launch.png

Conclusion

Hurray, this is another milestone in the quest to become an iPhone developer. Still we are not finished yet. As you may noticed when clicking any button on our View or the Done button on the keyboard will not make the keyboard disappear. Well that is the task for the page.