Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
346 views
in Technique[技术] by (71.8m points)

ios4 - Do code blocks completely replace delegates?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...