Show you how to fall in love with Block)

Source: Internet
Author: User
Block Definition
// Define the return type (^ block name) (parameter type) = ^ (parameter) {code}
Simple usage

After defining the block code block, you can use the entire block code as a variable. The variable can be a local variable or a global variable, which is also the most convenient part of block.

Assume that two arrays are to be generated, one containing five random numbers and one containing ten random numbers. The method for generating random numbers is defined as a closure, which can be directly accessed in the following text, as shown in

NSNumber *(^randArray)(void) = ^{      int rand = arc4random() % 100;      NSNumber *number = [NSNumber numberWithInt:rand];      return number;  };  NSMutableArray *array1 = [[NSMutableArray alloc] init];  NSMutableArray *array2 = [[NSMutableArray alloc] init];  for (NSInteger index = 0; index<10; index++) {      [array1 addObject:randArray];  }  for (NSInteger index = 0; index<5; index++) {      [array2 addObject:randArray];  }
Callback

The following istableViewCellThe example of Button Event Callback is also a headache for many people. block can be easily implemented and the layers are very clear.

The custom cell name isblockCell, Put one on the cell.switchControl. When the switch is clickedviewControllerYou can get the switch status and click events.

InblockCell.hDefine 1 inBlock

typedef void(^switchAction)(blockCell *);@property (nonatomic,copy)switchAction action;

Called in the switch Click Time eventswitchAction

blockCell.m

- (IBAction)switchToggle:(id)sender {    self.action(self);}

InviewControllerUse this custom cell to initialize the table

-(Uitableviewcell *) tableview :( uitableview *) tableview cellforrowatindexpath :( nsindexpath *) indexpath {nsstring * cellid = @ "blockcell"; blockcell * cell = [tableview cell: cellid]; cell. action = ^ (blockcell * cell) {// both the row and the switch nslog (@ "number of rows: % lD, switch state: % u", (long) indexpath. row, cell. switchbtn. on) ;}; return cell ;}
Block Encapsulation

Currently, many popular third-party libraries have changed callback to block. Previously, the delegate is especially handy and has been encapsulated and called directly to get the results I want. All of them are changed to block, I don't know how to get the block return value. I can only rewrite it once and generally.

In fact, it is very easy to encapsulate the block returned by a third-party library. You can use a block to access the page that returns the call.
AFNetworingI will talk about this later, but I have read it,githubThe readme on their home page is very clear and detailed. Please take a closer look at the children's shoes they want to know.readMe

Add Method

GitHub address: https://github.com/AFNetworking/AFNetworking

You can copy the class library to the project directory and add it. We recommend that you usecocoapodsEasy to update, and you do not need to manually import the framework, one-click setting

Encapsulation

Purpose: To call the corresponding method after passing the parameter to obtain the network return value.

Create a classWebRequestHere is an example for your reference.

# Import <Foundation/Foundation. h> # import "afnetworking. H "@ interface webrequest: nsobject-(void) requestnamewithid :( nsstring *) ID withsuccess :( void (^) (afhttprequestoperation * operation, Id responseobject, nsdictionary * mydata )) success Failure :( void (^) (handle * operation, nserror * error) failure; @ end @ implementation webrequest-(void) requestnamewithid :( nsstring *) ID withsuccess :( void (^) (optional * operation, Id responseobject, nsdictionary * mydata) Success Failure :( void (^) (afhttprequestoperation * operation, nserror * error) Failure {nsurl * url = [nsurl urlwithstring: @ "interface address spliced with ID"]; nsurlrequest * request = [nsurlrequest requestwithurl: url]; afhttprequestoperation * operation = [[afhttprequestoperation alloc] initwithrequest: request]; [operation restart: ^ (afhttprequestoperation * operation, Id responseobject) {nsdictionary * DIC = responseobject [@ "somekey"]; success (operation, responseobject, DIC ); // here, the network return value is passed to the three return values in the block defined by ourselves. DIC can be customized or not added, so that the objects that have been processed here can be returned, instead of calling it once, processing it once} failure: ^ (afhttprequestoperation * operation, nserror * error) {failure (operation, error); // consistent with the block in the method definition}];} @ end

Call

Webrequest * request = [[webrequest alloc] init]; [Request requestnamewithid: @ "123" withsuccess: ^ (afhttprequestoperation * operation, Id responseobject, nsdictionary * mydata) {// The returned value can be obtained here when the network is successful} failure: ^ (afhttprequestoperation * operation, nserror * error) {// network failure callback}];


Download Sample project


Fang zi said:

More and more databases are using blocks,^AsBlockWill not adapt at first glance, and will be in conflict with it if it is not used

Ios8 also has a considerable number of block operations, which have been around for more than two years.delegateIt's not far away. I believe you will fall in love with it after a little exploration and use. Good luck!

My QQ chat group: 130283564. You are welcome to join IOS developers who have more than half a year of experience. To add a group, please write an OC verification statement, or indicate the Open Source China.

Show you how to fall in love with Block)

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.