An article about block has written an article object-c-block review, but the relatively simple writing, can not reflect the importance of block in the actual development, the basic knowledge of block, you can refer to the previous blog. Block callbacks are used in the actual development of blocks in the callback process, both for Apple's official interface and for the interfaces of some third-party libraries. In many cases, block and gcd together, the most common scenario is that the app to go back to the background to take the data is time to take, the data after the successful we can update the UI page, this is the most common way of callbacks, can also be done by notification, If it is a single use notification no problem, if the request is more than the case, the amount of code will be a level.
Block Callback
Simple block notation, return type block name parameter, basically conforms to the method of writing, first look at one of the simplest block notation:
int (^BLOCKDEMO) (int a,int b) =^ (int a,int b) { return a+b; }; NSLog (@ "Blockdemo Result:%d", Blockdemo (90,72));
The final result is 162, simple and clear, it is easy to understand, now we first through the UITableView display background data, the effect is as follows:
Viewcontroller in the code, a simple implementation of the UITableView:
-(UITableView *) TableView {if (!_tableview) {_tableview = [[UITableView] Alloc] Initwithframe:cgrectmake (0, Cgrectgetwidth (self.view.bounds)-10, Cgrectgetheight (Self.view.bounds)-style:uitableviewstyleplain]; _tableview.rowheight = 40.0; _tableview.sectionheaderheight = 0.0; _tableview.sectionfooterheight = 0.0; _tableview.datasource = self; _tableview.delegate = self; } return _tableview;} -(Nsinteger) TableView: (UITableView *) TableView numberofrowsinsection: (nsinteger) section{return [Self.datasource Count];} -(UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *) indexpath{ UITableViewCell *cell=[[uitableviewcell Alloc]init]; Cell.textlabel.text=[self.datasource ObjectAtIndex:indexPath.row]; return cell;}
to extract data from Fetchdata in Fedataservice:
-(Nsmutablearray *) fetchdata{ nsmutablearray *mutablearray=[[nsmutablearray alloc]initwithobjects:@ "Blog Park" , @ "Flyelephant", @ "Http://www.cnblogs.com/xiaofeixiang", @ "iOS technology group: 228407086", nil]; return Mutablearray;}
Calls in the controller:
Self.dataservice=[[fedataservice Alloc]init]; Self.datasource=[self.dataservice Fetchdata];
It takes time to retrieve data from the background, and the network may not be able to take out the data, which can be recalled by block, redefining a dataservice in the Fetchdatasource Method:
-(void) Fetchdatasource: (void (^) (Nsmutablearray *array,nserror *error)) Fetchdatablock;
Note that the block argument here, Fetchdatablock equivalent to the parameter name, the preceding is the type, the implementation of the GCD added
-(void) Fetchdatasource: (void (^) (Nsmutablearray *, Nserror *)) fetchdatablock{ dispatch_time_t time= Dispatch_time (Dispatch_time_now, nsec_per_sec* (int64_t) 1.0); Dispatch_after (Time,dispatch_get_main_queue (), ^{ nsmutablearray *mutablearray=[[nsmutablearray alloc] initwithobjects:@ "Blog Park", @ "flyelephant", @ "Http://www.cnblogs.com/xiaofeixiang", @ "iOS technology group: 228407086", nil]; Fetchdatablock (Mutablearray,nil); });
A callback in the controller also achieves the above effect:
[Self.dataservice fetchdatasource:^ (Nsmutablearray *array,nserror *error) { if (!error) { Self.datasource=array; [Self.tableview reloaddata]; } }];
Block Extension
1. Stack blocks, heap blocks, and global blocks
When defining a block, the area of memory is in the stack, and the block is valid only in the range that defines it, so we can look at the following notation:
NSString *[email protected] "blog Park flyelephant"; void (^block) (); if ([string isequaltostring:@ "iOS technology Group: 228407086"]) { block=^{ NSLog (@ "Keso"); } else{ block=^{ NSLog (@ "Http://www.cnblogs.com/xiaofeixiang");} ; }
Block is defined first, then in the judgment of the block assignment, the final stack to save two blocks of memory, the call block outside of the judgment statement may be allocated to block memory overwrite, the result is sometimes correct, overwriting the time will cause the program crashes, The way to solve the above problem we can be stored in the heap memory by the block from the stack memory through copy, the code is as follows:
NSString *[email protected] "blog Park flyelephant"; void (^block) (); if ([string isequaltostring:@ "iOS technology Group: 228407086"]) { block=[^{ NSLog (@ "Keso"); } copy]; } else{ block=[^{ NSLog (@ "Http://www.cnblogs.com/xiaofeixiang"); } copy]; }
The block stored in the heap becomes the reference calculation type, when the reference count becomes 0 in the ARC environment will be reclaimed by the system, and the memory in the stack is automatically reclaimed by the system, so the first code stability is not guaranteed, there is a global block, the global block declared in global memory, the compilation period has been determined, It does not need to be created in the stack each time, the global block copy is an empty operation, so the global block cannot be reclaimed by the system.
2. Simplify code readability with typedef
In block callbacks we find that the object that passes in a block is sometimes not as straightforward as it seems, and we can define a block with a typedef simplification:
typedef void (^fetchblock) (Nsmutablearray *datasouce,nserror *error);
The method in DataService can be simplified in a number of ways:
-(void) Fetchdatasourcesimple: (fetchblock) block;
The implementation code is the same as the previous block implementation:
-(void) Fetchdatasourcesimple: (fetchblock) block{ dispatch_time_t time=dispatch_time (Dispatch_time_now, nsec_per_sec* (int64_t) 1.0); Dispatch_after (Time,dispatch_get_main_queue (), ^{ nsmutablearray *mutablearray=[[nsmutablearray alloc] initwithobjects:@ "Blog Park", @ "flyelephant", @ "Http://www.cnblogs.com/xiaofeixiang", @ "iOS technology group: 228407086", nil]; Block (Mutablearray,nil); });
The line pen hurriedly, unavoidably omission, if have improper, many advice ~
iOS Development-block Callback