What's delegation?

Discussion in 'Public Game Developers Forum' started by wootbean, Oct 15, 2009.

  1. wootbean

    wootbean Well-Known Member

    Feb 8, 2009
    5,549
    1
    36
    the next whiskey bar
    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? :eek:

    thanks for help
     
  2. PixelthisMike

    PixelthisMike Well-Known Member

    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:

    Code:
    - (void)showAlert
    {[INDENT]UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert!" message:@"This is an alert" cancelButtonTitle:@"Done" otherButtonTitles:nil];
    alert.delegate = self;
    [alert show];[/INDENT]}
    
    - (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
    {
    [INDENT]// do some stuff when "Done" button pressed
    ...[/INDENT]
    }
    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:

    Code:
    ...
    @interface MyViewController : UIViewController <UIAlertViewDelegate>
    ...
     
  3. lazypeon

    lazypeon Well-Known Member
    Patreon Bronze

    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.
     

Share This Page