You are on page 1of 10

Lesson

2: Displaying a MessageBox to the User



In this lesson we are going to modify the project developed in lesson one to have a
pop up message window appear when the button is tapped. To display messages to
the user, you use a UIAlertView. First lets see how to display one with a single
button that we will label OK. To display the message to the user we will apply
these steps:

1. Declare an instance of UIAlertView
2. Allocate memory for it
3. Initialize it setting the title and buttons
4. Display it to the user with the UIAlertView show method
5. Release the memory when done

Saying Hello World using a String
Lets modify the project from the previous lesson. Opening the
ViewController_iPhone.xib file, Ive dragged a Label to the View:



Now lets connect the label to code. First, open ViewController.h and type:

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@property(nonatomic,retain) IBOutlet UILabel *mylabel;

-(IBAction) sayHello:(id)sender;

@end

This @property statement is kind of technical, but to make iPhone apps you dont
have to know that much to get started, just put your statements like above when you
want to access a user interface object like a label in code. We can briefly describe it
here but dont get hung up on it for now. Read these articles for some discussion:

http://stackoverflow.com/questions/9859719/xcode-property-attributes-
nonatomic-copy-strong-weak

http://www.cocoawithlove.com/2008/08/in-defense-of-objective-c-20-
properties.html

Now open the ViewController.m file. When you create a property, you will need to
add a corresponding synthesize statement so that getter and setter methods are
automatically created to read and write to the objects properties:

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

@synthesize mylabel;

-(IBAction) sayHello:(id)sender{

NSLog(@"Hello World");

}

Now we can change the code in the sayHello Action to change the label on the
screen. This is done by writing:

-(IBAction) sayHello:(id)sender{
NSString *message = [[NSString alloc] initWithString:@"Hello
World!"];

mylabel.text = message;
}

Next, save your files then return to the XIB file. Click on Files owner, then look at the
Connections Inspector for Outlets:



Notice the mylabel object we created in our code is displayed here. Click on the
circle on the far right of mylable and hold the mouse button down, then drag it to
the label on your View. Now when we run the code we see upon a button click:



Saying Hello with an Alert View


Luckily, the first three tasks can be done in one line just like we did when initializing
the string. No changes to the user interface is necessary. We are just going to change
what happens when the button is tapped. Here is the old code:

-(IBAction)sayHello:(id)sender{

NSString *message = [[NSString alloc] initWithString:@"Hello


World!"];

mylabel.text = message;

[message release];

}

Were not going to use the label to display the message, so we delete the line
referencing the label (in fact, if you want you can delete the synthesize directive,
along with the variable declaration and property declaration, although its not
strictly necessary to get rid of all of that). Now our code looks like this:

-(IBAction)sayHello:(id)sender{

NSString *message = [[NSString alloc] initWithString:@"Hello


World!"];

[message release];

Now lets declare an instance of UIAlertView. For starters, to do it without working


about allocation and initialization, we would write:

UIAlertView *alert

We can allocate the memory for the variable alert in basically the same way we did
for the string variable. But this time of course, we use the class UIAlertView to
allocate the memory:

UIAlertView *alert = [[UIAlertView alloc]

Next, we can initialize it by using initWithTitle. Following this keyword we specify
the title, message, and buttons. Titles and messages can be input as string literals or
using variables. Since we already have a string called message in our method we can
go ahead and use that. We will use a string literal for the title, that way you can see
how to do it both ways in one step. OK that might be a little confusing, so here is
how we initialize it:

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"My
Program Message!" message:message
delegate:self cancelButtonTitle:@"OK"
otherButtonTitles:nil, nil];

Quick Aside: Strings in Your iPhone Apps


Something youve already noticed is that each time we assign a string literal to
something, we precede the string with the character @ and enclose it in double
quotes. So this is a valid string assignment:

@Hi There

But this is not:

Hi There

Make sure you always include your @ character at the beginning of a string, before
the first double quotation mark.

Now back to the code. We have used a new keyword nil to pass null pointers to a
few of the properties of the UIAlertView that we are not going to use. There is also a
new item called delegate that we will get to later. For now, just be sure to include
it whenever you set up a UIAlertView.

The title appears at the top of the UIAlertView when its displayed to the user. Weve
initialized it with a string literal:

initWithTitle:@"My Program Message!"

For the message, weve used our NSString *message variable:

message:message

The first button of the UIAlertView is called cancelButton by default, but the label
on the button is anything you specify. We tell it to display the phrase OK by writing:

cancelButtonTitle:@"OK"

Now, we need to call the show method. Whenever you need to call a method for
some object, enclose it in square brackets. So our instance variable is called alert
and we call its show method by writing:

[alert show];

At that point, were all done with the UIAlertView. If we did not select Automatic
Reference Counting when creating the app, we can release the memory:

[alert release];

However, if you created your app using Automatic Reference counting or ARC, this
line of code is not necessary. In fact including it will generate an error.

Lets go ahead and run in the simulator, and tap the button. This is what we get,
youre standard Hello World message box:




Now suppose that you wanted to display two buttons called Yes and No. Well
change the message and display the message box with two buttons by changing the
code like so:

-(IBAction)sayHello:(id)sender{

NSString *message = [[NSString alloc]


initWithString:@"Feeling Well Today?"];

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"My


Program Message!" message:message

delegate:self cancelButtonTitle:@"Yes" otherButtonTitles:@"No",


nil];
[alert show];
[alert release];

[message release];

}

We added a second button by setting otherButtonTitles to something other than nil.
Now when we run, this is what we get:




To add a third button, we can simply add to our list of other button Titles.
However, be aware that the cancel button appears at the bottom of a stacked list.
In other words if we type:

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"My
Program Message!" message:message
delegate:self cancelButtonTitle:@"Yes"
otherButtonTitles:@"No",@"Maybe So", nil];
[alert show];
[alert release];

This is what we see:




It might make more sense to arrange things as Yes-No-Maybe So. So we will set the
cancel button to Maybe So. Then we will put Yes and No for the other button
titles:

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"My
Program Message!" message:message

delegate:self cancelButtonTitle:@"Maybe So"


otherButtonTitles:@"Yes",@"No", nil];
[alert show];
[alert release];

This gives us what we want:

Lesson Summary
In this lesson we learned how to create a UIAlertView and display it to the user, with
one or more buttons. In the next lesson, we will learn how to determine which
button the user tapped, and how to record events and data for debugging purposes
in xcode.

You might also like