Blocks vs Delegates

15,845

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. ;)

Share:
15,845
Frederick C. Lee
Author by

Frederick C. Lee

My raison d'être: To exploit the power of Apple (iOS/OSX) and open-source technologies. To promote intuitive client/server paradigms using the distributive ‘cloud computing’ paradigm whilst leveraging the power of Apple’s iOS. I enjoy cool clean air and water in tranquility. I enjoy aquaria. I admire well-written works of literature & logic; and the arts...as I do cuisine.

Updated on July 22, 2022

Comments

  • Frederick C. Lee
    Frederick C. Lee almost 2 years

    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?