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?
Callbacks are similar in function to the delegate pattern. They do the same thing: letting other objects know when something happened, and passing data around. What differentiates them from the delegate pattern, is that instead of passing a reference to yourself, you are passing a function.
Difference between protocol Delegate and Closures –In the protocol method, we use the call by delegate method then use it but in closer, we can call it directly, there is no need for the delegate method.
My simple rule: if something requires one function as it's interface, a callback is usually a good solution. If more than one function is required, especially when they're required for the basic function of an object, a Delegate is probably a better solution.
Protocol is a set of methods (either optional or required) that would be implemented by the class which conforms to that protocol. While, delegate is the reference to that class which conforms to that protocol and will adhere to implement methods defined in protocol.
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:
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.
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).
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. ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With