SNV7
SNV7

Reputation: 2593

How does a delegate method know when to be called

I'm just wondering how exactly does a delegate method know when to be called? For example in the UITextFieldDelegate protocol the textFieldDidBeginEditing: method is called when editing begins in the textfield (provided I implemented this method).

So how exactly does the code to detect when to call textFieldDidBeginEditing:? Does the system just check if textFieldDidBeginEditing: is already implemented and if it is it runs that method? Is there something under the hood that I'm not seeing?

Upvotes: 3

Views: 291

Answers (2)

Conrad Shultz
Conrad Shultz

Reputation: 8808

Exactly.

I can't vouch for how Apple's framework code is implemented under the hood, but an exceedingly common refrain is:

if ([[self delegate] respondsToSelector:@selector(someInstance:didDoSomethingWith:)]) {
    [[self delegate] someInstance:self didDoSomethingWith:foo];
}

This allows you to have optional delegate methods, which appears to be your question.

Upvotes: 3

CrimsonDiego
CrimsonDiego

Reputation: 3616

The code doesn't 'detect when to call' a delegate method. The textField receives an event, and calls the method on it's delegate (which has the textFieldDidBeginEditing: method implemented).

In short, when you tap the textfield to start editing, the textField says 'oh, I'm editing now!' and internally calls [self.delegate textFieldDidBeginEditing:self], where the delegate is the instance in which you've set to be the delegate (usually a UIViewController subclass)

Upvotes: 0

Related Questions