P81 textFieldShouldReturn. How can we use this here?


What i am confused on is how can we use this method textFieldShouldReturn. The only place i see where this is defined is in UITextFieldDelegate protocol but, this protocol is not declared in Whereami.h. So how can we use this method?

It’s like it’s saying you can use methods in protocols without making the delegate class conform to the protocol.

Please help!



I think the fact that the textFieldShouldReturn method is defined in a protocol may be the confusion here.

In this example the UITextField has a delegate that you have set to the whereamiAppDelegate object.

UITextField has been designed such that when the user taps the return button it will check to see if the object, that it’s delegate points to, implements the textFieldShouldReturn method. If it does then it will call it.

If you put the following in whereamiAppDelegate.m you can see this (and all the other requests) in action

- (BOOL) respondsToSelector: (SEL) aSelector
    NSLog (@"I am being asked if I respond to %s", (char *) aSelector);
    return ([super respondsToSelector: aSelector]);

Regarding protocols:
When you formally adopt a protocol in a class by using you are saying that you have implemented all the @required methods that the protocol has defined and the compiler will check that you’ve implemented everything you’ve committed to. A guarantee if you like.

So if theProtocol has two @required methods “requiredMethodOne” and “requiredMethodTwo” then the complier will warn you if you haven’t implemented both methods in that class.

If you don’t formally adopt the protocol i.e. don’t add then there is nothing to stop you implementing “requiredMethodOne” and “requiredMethodTwo”. In this case you are informally conforming to the protocol. Everything will still work but the compiler doesn’t guarantee it because you didn’t ask it to.

In the case of UITextFieldDelegate - all the methods happen to be @optional so you can implement any/none/all of them that you are interested in - if you do then they will be called at the appropriate point - if not then they won’t.

The designers of UITextField have decided to put these methods in a protocol (and it is a neat way of advertising which messages an object sends) but whether they had or not it would still work the same way. In fact (not advised) I think you can remove all the , ignore all the warnings and it will still run ok !
In contrast - you could add to the whereamiAppDelegate to make its responsibility explicit.

Hope that helps.