Let's say you want to present the user with an alert, and you want a method to run when the user touches one of the buttons. The problem is, how do you know what method to call, on which object, when someone touches a button?
In order for a class to be a delegate, you have to declare it as such. In the above example, lets say you have an ApplicationController object which controls the flow of your application. In the declaration, we would say
@interface ApplicationController : NSObject <UIAlertViewDelegate>
This tells the compiler that ApplicationController is going to implement some methods in the UIAlertViewDelegate protocol. We look that protocol up in our documentation, and see a list of methods. As we want to do something when a button is pressed, we see:
alertView:clickedButtonAtIndex:
- Sent to the delegate when the user clicks a button on an alert view. This method is optional.
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
So, if we implement a method in ApplicationController called alertView:clickedButtonAtIndex
, create an ApplicationController object, and then set that object as the delegate of an alert we show, everything is set up. As soon as someone presses a button on the alert, the alertView:clickedButtonAtIndex
method will be called, passing in the alertView and the index of the button pressed.
This allows you to do whatever you want with that information. A simple case statement:
if( buttonIndex == 0 ) {
_myString = @"Pressed the button";
} else {
_myString = @"Pressed the other button";
}
The Objective-C reference docs are very, very good, and all the delegate protocols are pretty self explanatory.