Current location - Quotes Website - Personality signature - The difference between ios block and delegate
The difference between ios block and delegate
1.*** Same function:

The methods in Block and Delegate can be understood as callback functions, which get and execute code fragments when something happens.

2. Blocks (code blocks)

Advantages: It is a lightweight callback and can directly access the context. The place where blocks are used and the place where blocks are implemented are in the same place, which makes the code organization more coherent.

3. Representative (agent)

This is a relatively heavyweight callback.

Disadvantages:

Because the declaration and implementation of methods are separated, the consistency of code is not very good.

Agents often need to store some temporary data.

Advantages:

The callback function of the agent can be a group of multiple functions, and different callback functions can be called at different times.

4. How to choose which one to use

1. When there are more than three callback functions, the proxy is better.

2. Using code blocks is easy to cause circular references, and agents will not have this problem.

3. In other cases, the code block has priority.

There are three types of blocks:

Temporary, only used in the stack, not stored.

For example, the foreach traversal of an array, the blocks used in this traversal are temporary and will not be stored.

It needs to be stored, but it will only be called once, or there is a completion period.

For example, an animation of UIView needs to be notified to the outside with a block after the animation is completed. Once the block is called, it can be deleted.

It needs to be stored and may be called many times.

For example, the click event of a button, if implemented by block, needs long-term storage and will be called many times. After calling, the block cannot be deleted, and there may be a next button to click.