PDA

View Full Version : delegat delegate delegate




bytezone
May 8, 2009, 12:50 PM
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



ghayenga
May 8, 2009, 02:53 PM
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

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];
}

PhoneyDeveloper
May 9, 2009, 01:16 PM
Look at Apple's Cocoa Fundamentals Guide. It's included in Xcode.

firewood
May 9, 2009, 09:02 PM
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.


imho