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?
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.
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.
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.
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.
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