Search code examples
objective-cios4

id<delegate> in chatty app


in the chatty app if found this declaration , but i couldn't find an explanation for it anywhere. id delegate

where RoomDelegate is a class.What is happening here?


Solution

  • I find the easiest way to explain this would be through a common delegate in UIKit, like UIAlertViewDelegate. Here's some sample code:

    In your .h file, you would say that your class conforms to a delegate, like this:

    @interface Foo : UIViewController <UIAlertViewDelegate> { // ...
    

    This tells the compiler that the class Foo implements some or all methods of a delegate.

    When you instantiate a UIAlertView, you specify what the delegate is for the object:

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Title" 
                                                    message:@"Message"
                                                   delegate:self
                                          cancelButtonTitle:@"Okay"
                                          otherButtonTitles:@"Cancel", nil];
    [alert show];
    [alert release];
    

    Note that we're saying self is the delegate.

    Now, you want to implement the necessary methods:

    - (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
        NSLog(@"%d got clicked", buttonIndex);
    }
    

    For UIAlertView, there's a property of type id<UIAlertViewDelegate>, which ties this back to your original question.

    I'm fairly new to Objective-C/iPhone development and one thing I found to be super useful is to look for an associated xxxxDelegate in the "Overview" section of a class. You're bound to find useful (in other languages' parlance) events that get fired for common actions.

    Hope this helps!