delegat delegate delegate

Discussion in 'iOS Programming' started by bytezone, May 8, 2009.

  1. bytezone macrumors member

    Apr 20, 2009
    I am having a hard time understading delegates in objective c.Everywhere I have read "instead of subclassing, u can use delegates....". Can anyone give me a link which explain the use of delegates over subclassing.

    "UIApplication defines a delegate that must adopt the UIApplicationDelegate protocol implement one or more of the methods." Can you explain what this means in plain words...???Thanks
  2. ghayenga macrumors regular

    Jun 18, 2008
    A delegate can be any class that implements the required functions. Typically you'll make your viewController the delegate for something, but it can be anything.

    You don't subclass UITextField for instance. You set another object as it's delegate and declare that object as implementing the UITextFieldDelegate.

    In your header file:

    @interface LoginViewController : UIViewController <UITextFieldDelegate> {

    IBOutlet UITextField *userNameField;
    IBOutlet UITextField *passwordField;


    Then in your source file implement whatever methods of the UITextFieldDelegate that you are interested in and they will be called when those events are occur on the textField.

    - (void)viewDidLoad
    userNameField.delegate = self;
    passwordField.delegate = self;

    - (void)textFieldDidBeginEditing:(UITextField *)textField
    [self setViewMovedUp:50];
  3. PhoneyDeveloper macrumors 68040


    Sep 2, 2008
    Look at Apple's Cocoa Fundamentals Guide. It's included in Xcode.
  4. firewood macrumors 604

    Jul 29, 2003
    Silicon Valley
    Instead of creating a whole subclass to do something special, in Obj C, you can often just have an existing class do that "something special" for you. The way to tell the compiler which existing class is doing that for you, is that you declare it to be a delegate for the class that you would have subclassed in another language.

    So instead of having a whole bunch of subclasses to customize the behavior of your buttons, text fields, etc., you can just tell the compiler to let the view controller do that for you.

    Keeps all the customization for a view in that view, instead of scattered about among more smaller objects.

    Of course, if you want to replicate a magic button in ten zillion different kinds of views, then it might be better to create a subclass for your magic button anyway.

    There are always trade-offs.


Share This Page