O'Reilly logo

Beginning iOS 5 Application Development by Wei-Meng Lee

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

PROTOCOLS

In Objective-C, a protocol declares a programmatic interface that any class can choose to implement. A protocol declares a set of methods, and an adopting class may choose to implement one or more of its declared methods. The class that defines the protocol is expected to call the methods in the protocols that are implemented by the adopting class.

The easiest way to understand protocols is to examine the UlAlertView class. As you have experienced in the various chapters in this book, you can simply use the UlAlertView class by creating an instance of it and then calling its show method:

UlAlertView *alert = [[UlAlertView alloc]
                          initWithTitle:@“Hello”
                                message:@“This is an alert view”
                               delegate:self
                      cancelButtonTitle:@“OK”
                      otherButtonTitles:nil];
[alert show];

The preceding code displays an alert view with one button — OK. Tapping the OK button automatically dismisses the alert view. If you want to display additional buttons, you can set the otherButtonTitles: parameter like this:

UIAlertView *alert = [[UIAlertView alloc]
                          initWithTitle:@“Hello”
                                message:@“This is an alert view”
                               delegate:self
                      cancelButtonTitle:@“OK”
                      otherButtonTitles:@“Option 1”, @“Option 2”, nil];
[alert show];

The alert view now displays three buttons — OK, Option 1, and Option 2. How do you know which button was tapped by the user? You can determine that by handling the relevant method(s) that will be fired by the alert view when the buttons are clicked. This set of methods is defined by the UIAlertViewDelegate ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required