Blocks vs Delegates [duplicate]

2019-01-22 23:48发布

问题:

Possible Duplicate:
Do code blocks completely replace delegates?

I just encountered the following declaration from a forum:

"Delegates is the past. Blocks are the future."

1) Are blocks the preferred way to do 'delegation' duties over delegates?
2) Is there any particular benefit of using a delegate vs a block?

回答1:

I think there's a slight misunderstanding in what delegates do and what blocks do.

In Objective-C, there are three ways to handle callbacks:

  1. Delegation -> where you make one object the delegate of another object and you have to specify which kinds of events generated by the "parent" object the delegate object will respond to.

  2. Target-Action -> typical in UI interactions, where a UI subview (button, slider, etc) generates an event based on some user input (for example a touch/tap) that is handled by a predefined event handler (typically some Objective-C method that the developer specifies).

  3. Notification -> where an object registers itself with an instance of NSNotificationCenter to "listen" for events of any type and responds to one or more of those events.

A block is not by itself a way to handle delegation, or any other callback.

They are self-contained pieces of code that have access to the local variables and parameters of the calling method. They can be used to define behavior in a bunch of different contexts. The main benefit of a block (as I see it) is that it can simplify code by eliminating extraneous overly-specific methods that would clutter your codebase. Blocks help to localize code to where it makes the most sense: right there within the callback mechanism.

Basically, using them enhances readability and makes code more maintainable.

Whether these benefits make blocks the 'preferred' method of handling callbacks is definitely a matter of personal opinion and experience. ;)