Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

bytezone

macrumors member
Original poster
Apr 20, 2009
64
0
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
 
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];
}
 
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
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.