Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do code blocks completely replace delegates?

Tags:

Now that blocks are finally supported for iphone/ipad development, do these completely remove the need for delegates or are delegates still cleaner as a complete interface implementation while blocks are more appropriate for single tasks?

like image 222
LK. Avatar asked Jan 03 '11 12:01

LK.


People also ask

Why we use delegates instead of methods in C#?

Delegates allow methods to be passed as parameters. Delegates can be used to define callback methods. Delegates can be chained together; for example, multiple methods can be called on a single event. Methods don't have to match the delegate type exactly.

What are delegates in C# used for?

Understanding delegates in C# Delegates are used to define callback methods and implement event handling, and they are declared using the “delegate” keyword. You can declare a delegate that can appear on its own or even nested inside a class.

How do you declare a delegate in C#?

A delegate can be declared using the delegate keyword followed by a function signature, as shown below. The following declares a delegate named MyDelegate . public delegate void MyDelegate(string msg); Above, we have declared a delegate MyDelegate with a void return type and a string parameter.


1 Answers

I've been searching for official documentation on this but have yet to find any. Based on reviewing the new classes exposed in iOS 5 and those additions made to pre-existing classes, I'm recommending to my team to presume a delegate protocol but to provide a block instead when there is a direct causal nexus between that specific call and performance of the block.

So, as a rule of thumb, a delegate protocol is correct when there's a need for ongoing communication, the actions causing the communication are diffuse or the actions are emanating from a third source. Blocks are primarily associated with asynchronous actions and single-shot classes in particular.

EDIT: so, some examples:

UIScrollViewDelegate is correctly a delegate protocol because (i) there's a wide range of things that may need to be communicated; (ii) they may need to be communicated in any order and at any time; and (iii) they will be communicated for reasons beyond the delegate's control.

NSURLConnection +sendAsynchronousRequest:queue:completionHandler: correctly takes a block to deliver results because (i) there's exactly one result to report; and (ii) the report comes back as a direct consequence of action taken by the caller.

like image 158
Tommy Avatar answered Nov 07 '22 06:11

Tommy