Sunday, October 05, 2008

iPhone dev 15 - How do I monitor the events that the textfield sends? Where does it send them to?

Last time I wondered what happens with the textfield events. Now I've read a bit more about delegates, how to use them in practice. Controls have a "delegate", called such because application-specific behavior is delegated to it. For textfields the delegate protocol is UITextFieldDelegate. To implement protocols, angle brackets are used when declaring a class, so here is the code I used in my declaration in MyTextFieldDelegate.h:

@interface MyTextFieldDelegate : NSObject {
- (BOOL)textFieldShouldReturn:(UITextField *)exTextField;

Then implementation in MyTextFieldDelegate.m is very simple:

#import "MyTextFieldDelegate.h"
@implementation MyTextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)exTextField {
[exTextField resignFirstResponder];
return YES;

I found that "resignFirstResponder" line on some Mac development forum. I tried to read the docs a bit to learn what it means. The docs say unhelpfully that it makes something release the first responder status, whatever that is. In plain english I discovered it means that it makes the soft keyboard disappear, at least in this case.

Well above you see the delegate class, but that wouldn't do much if the textfield doesn't know about its delegate. I think this part must be slightly wrong because I'm never releasing the objects I create, but as an initial test this worked:

MyTextFieldDelegate *x = [[MyTextFieldDelegate alloc] init];
[x retain];
UITextField *testText = [[UITextField alloc] initWithFrame:testFrame];
testText.delegate = x;

The dot notation surprised me. After all the talk about automatically synthesized getters and setters, I expected to actually have to call methods to set variables. After reading the docs a bit more, it turns out that I actually AM calling a method here! The dot notation in Objective-C turns out to be exactly the same here as calling [testText setDelegate:x] and the dot notation is just a shortcut to it. This is very clever, because it allows you expose properties conveniently, but at the same time if necessary allows you to run code when they are accessed.

I'm starting to like this more and more, but memory management still confused me. I wonder how to see what I am failing to release? I don't want to leak memory on someone's iPhone.