The choice of blocks or delegates during the development process

Source: Internet
Author: User
Tags documentation naming convention


Generally in this case, I like to ask myself: "If the question is to Apple, what will he do?" Of course, we all know that Apple certainly knows how to do this, because at one level, Apple's documentation is a guide to how we use design patterns.



So we need to look at the circumstances in which Apple uses delegate and block, and if we find out how Apple makes this choice, we can build rules that can help us make the same choices in our own code.



To find out where Apple uses delegate is simple, as long as we search for "delegate" in official documents, we get a lot of classes that use delegation.



But it's a bit difficult to search Apple for documents about using blocks, because we can't search directly for "^" in the document. However, Apple has a good naming convention when it comes to declaring methods (which is also a prerequisite for our mastery of iOS development). For example, a method using NSString as a parameter, the method of selector will have a string word, like initwithstring;datefromstring; Startspeaingstring.



When the Apple method uses block, this method will have "Handler", "completion" or simple "block" as selector, so we can search the standard iOS API documentation for these keywords, Used to build a list of trusted block use cases.



1. Most delegate protocols have several sources.



Take the example I'm looking at Gkmatch (a Gkmatch object provides a peer-to-peer network between a group of devices that are connected to Game Cen TER is an object that is used in the iOS API to provide a set of devices to connect to the game Center point-to-point Network. You can see from this class that the source of the message is: When the data is received from other players, when the player has switched status, when an error occurs, or when a player should be invited again. These are different events. If Apple uses block here, there are two possible ways to solve this problem:



The corresponding block can be registered for each event, which is obviously unreasonable. (If someone writes a class that does this in objective-c, they are the probably an asshole.)



Create a block that can accept any possible input



1



void (^matchblock) (Gkmatchevent eventtype, Player *player, NSData *data, Nserror *err);



Obviously this is neither easy nor easy to read, so you may never have seen such a solution. If you've seen a solution like this, but it's obviously a terrible line of code, you don't have the energy to maintain it.



Therefore, we can draw a conclusion: if the object has more than one different event source, use delegation.



2. An object can only have one delegate



Because an object can only have one delegate, and it can only communicate with this delegate. Let's take a look at the Cllocationmanager class, where the location manager notifies only one object (with and only one) when the location is found. Of course, if we need more objects to know about this update, we'd better create other location manager.



Some people here may think, if Cllocationmanager is a single case? If we cannot create other instances of Cllocationmanager, we must constantly switch the delegate pointer to the object that needs the geographic data ( Or create a sophisticated broadcast system that only you understand. So, it seems, delegatetion doesn't make much sense in a single case.



The best example to prove this is uiaccelerometer. In earlier versions of iOS, the singleton accelerometer instance had a delegate, causing us to switch occasionally. This stupid question was modified after the iOS version, and now any object can access the Cmmotionmanager block without blocking other objects from receiving updates.



Therefore, we can draw another conclusion: "If an object is a single case, do not use delegation".



3. The general delegate method will have a return value



If you look at some delegate methods (almost all DataSource methods) have a return value. This means that the delegating object is requesting the state of something (the value of the object, or the object itself), while a block can reasonably contain state or at least infer state, so the block is really an attribute of the object.



Let's think about an interesting scenario, if you ask a block question: "What do you thinking about Bob?" Block might do two things: send a message to capture the object and ask the object what to think of Bob, or return a captured value directly. If a response to an object is returned, we should get the object directly over the block. If it returns a captured value, then this should be an object's property.



From the above observations, we can conclude that if the object's request has additional information, it should use the delegation



4. Process vs Results (processes vs. Results)



If you look at Nsurlconnectiondelegate and nsurlconnectiondatadelegate, we can see the message in protocol: What I'm going to do (such as: Willsendrequest, will send a request , so far I know the information (such as: Canauthenticateagainstprotectionspace), I have finished these (Didreceiveresponse, received the requested reply, that is, complete the request). These messages form a process, and the delegate that are interested in the process will be notified at each step.



When we look at the handler and the complete method, we find that a block contains a response object and an Error object. Obviously there's no interaction between "where I am, what I'm doing".





From the above we can draw two key points. First, if you use block to request a request that might fail, you should use only one block. We can see the following code:



[Fetcher makerequest:^ (ID result) {



Do something with result



} error:^ (Nserror *err) {



Do something with error



}];



The above code is significantly more readable than the following block (the author says this is his humble opinion, but personally think it is not so serious)



[Fetcher makerequest:^ (id result, nserror *err) {



if (!err) {



Handle result



} else {



Handle error



}



}];


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.