The primary principle of Delegate
Analysis of the Delegate principle
In class B, a method needs to pass a value to A and perform certain actions.
How can this be implemented?
First, B needs to know who to pass the value to and then call A.aFunc().
I understand that you want to know the principle without looking at the code, so I’ll simplify it as much as possible.
Classes A and B
1 | A.swift |
The above code doesn’t work, why?
Because there is no reference to A in class B, if we pass A directly, we’ll have to modify class B’s code, and thus lose the encapsulation.
Let’s see how Delegate can implement this mechanism:
Delegate
Since B needs to send a message externally, let’s start with B:
1 | A.swift |
After steps 1, 2, and 3, it still won’t work, why?
Because A doesn’t know that B has delegated the task, they’re not connected.
1 | A.swift |
Success!
Think about common code snippets, like:
1 | mScrollView.delegate = self |
Do you feel enlightened now?
I’ll talk about SEL
and Block
in a couple of days.
I feel like I haven’t explained it clearly, so if you have any questions or need further clarification, feel free to leave a comment and we can discuss it.
Translated by gpt-3.5-turbo