Block use detailed, block and agent advantages compared to

Source: Internet
Author: User

Block is an extension of the C language introduced by ios4.0+ and Mac OS X 10.6+ to implement the features of anonymous functions.
Block is an attribute added by Apple Inc. for C, C + +, and objective-c, allowing these languages to create closures using the syntax of a class lambda expression.
Closures are functions that can read other functions ' internal variables. is to see the invocation parameters (such as sending a request) and the result of the response in a continuous code request. So the use of block technology can abstract a lot of common functions, improve the readability of code, maintainability, encapsulation.
Unlike the proxy declaration of a proxy function, in the call of the class to implement the function, let people inexplicable surprise, if a page can send multiple requests, and multi-touch trigger to send multiple requests simultaneously, the proxy function of the page is difficult to distinguish is the result of the request, the random parsing of the message can easily crash. Some people say I send a request on a daisy, the message does not return, do not let other requests. Tell you this does not work, the reason is that the pop-up chrysanthemum is a thread, the call thread will return successfully, but you start the thread is added to the main course and it takes time to actually run, it takes about 130 milliseconds, and the prompt Chrysanthemum prompt box is also refreshing the UI thread. So when you click on the two button to send a request or toggle the page at the same time two fingers, when the first button and Daisy, but before the Chrysanthemum appears before the click on the other button, then you sent two requests in a row. Then you use the proxy implementation when it is difficult to separate the message, only your response message with the message type may be divided, if the server does not strong enough, when an exception, find not to send a request, give you a generic error response message, you only dumbfounded. Such multiple messages in a function parsing is also not conducive to encapsulation.
The most typical block of blocks is the afnetwork third-party library, which is known for its size. it resolves the send function to find its own corresponding response message. Typical examples of proxies see my article, "Implement your own asynchronous send request and picture": http://blog.csdn.net/jia12216/article/details/47043935.

Bloc first you declare the Bloc object in the. h file, and of course the parameters you return can be defined yourself:
typedef void (^requestcompletionblocks) (nsdictionary *result,bool successed);
typedef void (^socketlinesuccessblocks) (BOOL successed);
typedef void (^socketlinefailedblocks) (BOOL successed);

@property (nonatomic,weak) requestcompletionblocks Myblock; Block return parameters
@property (nonatomic,weak) socketlinesuccessblocks Socktlinesuccessblock; Successful connection
@property (nonatomic,weak) socketlinefailedblocks Socktlinefailedblock; Failed connection

-(void) Socketconnecthost: (socketlinesuccessblocks) onsuccesscpmlention
Failcompltion: (socketlinefailedblocks) onfailcompltion//socket connection

Implementing the function in a. m file is possible.
Socket connection
-(void) Socketconnecthost: (socketlinesuccessblocks) onsuccesscpmlention
Failcompltion: (socketlinefailedblocks) onfailcompltion//socket connection
{
This store sends the request object and responds to the request object to the global variable
Self.socktlinesuccessblock = onsuccesscpmlention;
Self.socktlinefailedblock = onfailcompltion;
This is called another block function.
[[Checkreachability sharedcheckreachability] checkreachability:^ (networkstatus status) {
if (status = = Notreachable)
{
No network return failure
Onfailcompltion (NO);
}
Else
{
Self.socket = [[Gcdasyncsocket alloc] initwithdelegate:self delegatequeue:dispatch_get_main_queue ()];

        NSError *error = nil;        [self.socket connectToHost:self.socketHost onPort:self.socketPort withTimeout:-1 error:&error];        //请求响应的成功消息在另一个socket线程函数里返回    }}];

}

The success message for the request response is returned in the socket thread function

Pragma mark-Connection success Callback
    • (void) Socket: (Gcdasyncsocket ) sock didconnecttohost: (nsstring ) host port: (uint16_t) port
      {
      Backstage can also be used
      [Self.socket performblock:^{
      Self.socket.enableBackgroundingOnSocket = YES;
      // }];
      NSLog (@ "Socket connected successfully");
      STATUS = Socketonline;
      Self.socktlinesuccessblock (YES);

      Self.readhead = YES;
      [Self.socket readdatatolength:10 withtimeout:-1 tag:1];

}

The invocation of the block function everyone knows:
Server dropped, re-connected
[Self socketconnecthost:^ (BOOL successed) {
if (successed)
{
Processing when the service returns successfully
}
Else
{
Processing of processing failures returned by the server
}

        } failCompltion:^(BOOL successed) {             //异常时的处理,通常指非服务器返回的异常        }];

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Block use detailed, block and agent advantages compared to

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.