★ TouchArcade needs your help. Click here to support us on Patreon.

What's delegation?

10-14-2009, 08:42 PM
Joined: Feb 2009
Location: the next whiskey bar
Posts: 5,549
What's delegation?

n00b iPhone programmer here. I've just started research on the objective-c language and the anatomy of an iPhone application...one thing I don't understand already is delegation, which seems to be a pretty big concept. I read these guides and references and whenever they talk about objects and their delegates I get confused...I think I get that it's one object sending messages to another telling it to do something? Which one is the delegate?

thanks for help
10-14-2009, 09:38 PM
Joined: May 2009
Location: Palmerston North, New Zealand
Posts: 464
The delegate is basically an object which you designate to receive messages from another object. These messages are usually fired in response to events such as a view being displayed or a button being pressed. The delegate object can be any object as long as it adopts the required protocol.

For example you might be coding somewhere inside MyViewController.m and you create a UIAlertView as follows:

- (void)showAlert
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert!" message:@"This is an alert" cancelButtonTitle:@"Done" otherButtonTitles:nil]; alert.delegate = self; [alert show];
} - (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
// do some stuff when "Done" button pressed ...
So this code sets the alert views delegate so that a touch on the alert views button (in order to close the alert) can be captured.

In order to set the delegate to self MyViewController must adopt the UIAlertViewDelegate protocol like so:

@interface MyViewController : UIViewController <UIAlertViewDelegate>

Check out Sheepish, 100+ levels of puzzle fun! With sheep!
And more about us: www.pixelthismobile.com
plus+ id: Newtz
10-14-2009, 10:18 PM
Joined: Feb 2009
Location: San Jose, CA
Posts: 546
I think about delegates as a class that is 'delegated' a task by another class. Basically you have a class (the 'manager') and instead of handling a task, he tells his delegate (his 'employee') to do it instead. The manager only know how to do the task one way. But, by telling his employees to handle the task, he can have it completed many different ways.

In the above example, UIAlertView doesn't handle the event; rather, it receives events and then tells some other class to handle it. In this way, you can customize the behavior of the application. Maybe you just want to consume the events and not do anything, maybe you want to continue passing them, etc... Since UIAlertView delegates responsibility instead of handling the action itself, you can do whatever you want.