How does a delegate method know when to be called

2019-07-04 03:28发布

问题:

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?

回答1:

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.



回答2:

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)