fuzzygoat
fuzzygoat

Reputation: 26223

With & Without UITextFieldDelegate?

I am curious about conforming a class to UITextFieldDelegate, in the past I have always added it to enable access to methods defined within the protocol. However this last time I forgot to add it, only realising later that it was missing. My question is why does it work with or without, I thought it was needed to correctly access the protocol methods?

@interface MyController : UIViewController <UITextFieldDelegate> {
    UITextField *text_001;
}
@property(nonatomic, retain) IBOutlet UITextField *text_001;
@end

OR:

@interface MyController : UIViewController {
    UITextField *text_001;
}
@property(nonatomic, retain) IBOutlet UITextField *text_001;
@end

WITH:

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    NSLog(@"Return: ... ");
    [textField resignFirstResponder];
    return YES;
}

Cheers Gary

Upvotes: 2

Views: 579

Answers (1)

Ben Gottlieb
Ben Gottlieb

Reputation: 85522

Delegate declarations are really just there as compiler hints; obviously, you still have to implement the underlying methods. However, the main purpose is to let the compiler double check you when assigning them. If you try to manually (in code, as opposed to IB) assign a delegate which wasn't declared as such, you'll frequently get a compiler warning.

Since Objective-C uses duck-typing for most stuff (if it walks like a duck and quacks like a duck; if it responds to -textFieldShouldReturn:, etc), you're pretty safe.

Upvotes: 5

Related Questions