Since the advent of block, many APIs have started to adopt such a structure, thus, there are many advantages of block, here are some simple usage summarized as follows:
First, how to declare a block variable
We declare the block type with the ^ symbol in the following form:
void (^myblock) ();
Where the first void is the return value, can be any type, in the middle brackets ^ followed by the name of the block variable, I named it Myblock, the last parenthesis is the argument, if the multi-parameter, can be written as follows:
Int (^myblock) (int,int);
Also, you can name the parameter:
Int (^myblock) (int a,int b);
Many times, we need to use our declared block type as a function parameter, and there are two ways:
1,-(void) func: (int ^ () (int a,int b)) block;
The second way is to define a new type through a TypeDef, which is also the way in most cases:
2, typedef int (^myblock) (int a,int b);
-(void) Func: (myblock) block;
Second, how to achieve a block
Since a block can be declared as a variable, it must be implemented, just like the assignment of other types of variables. My own understanding of block is that it is a block of code, so assigning it a value is a piece of code:
typedef int (^myblock) (int,int); @interface Viewcontroller () {Myblock block1;} @end @implementation viewcontroller-(void) viewdidload {[Super viewdidload]; Additional setup after loading the view, typically from a nib. Block1 =^ (int a, int b) {return a+b; }; NSLog (@ "%d", Block1);}
The result here is 2, and from here we can see that the function of block and function is very similar.
Note: 1, in the above code Block1 is an object, if you print directly will print the object address
2, Block (), plus the following parentheses is the execution block statement blocks
Third, the subtle relationship of accessing objects in block
1, if you are in a block block only access to the object, but not to modify his operation, there is no problem:
-(void) viewdidload {[Super viewdidload]; Additional setup after loading the view, typically from a nib. int tem=2; Block1 = ^ (int a,int b) {int count= tem+1; return count; }; NSLog (@ "%d", Block1);}
And if I modify it directly in block blocks, the compiler will make an error:
Block1 = ^ (int a,int b) {tem+=1; return tem+1; };
Why this happens, according to speculation, may be inside the block will access the variables are backed up a copy, if we are internally modified, external variables are not modified, we can print the variable address to prove this:
-(void) viewdidload {[Super viewdidload]; int tem=2; NSLog (@ "%p", &tem); Block1 = ^ (int a,int b) {NSLog (@ "%p", &tem); return tem+1; }; NSLog (@ "%d", block1); }
The printing results are as follows:
As you can see, the address of the variable has changed.
2. What did __block do?
in order to be able to access and modify external variables in block blocks, we often declare variables as __block types, and through the above principle, we can find that this keyword only does one thing, If a variable that is not added to this keyword is accessed in a block, it accesses the copy of the block itself, which was created when the block was created, and accesses the variable that adds the keyword, and accesses the variable that corresponds to the variable's address. We can prove it by code:
-(void) viewdidload {[Super viewdidload]; Additional setup after loading the view, typically from a nib. int tem=2; Block1 = ^ (int a,int b) {return tem+a+b; }; tem=4; NSLog (@ "%d", block1); Block1 = ^ (int a,int b) {return tem+a+b; }; __block int tem2=2; tem2=4; NSLog (@ "%d", Block1);}
Results:
3, a little expansion
Thus, we can understand that if the object in the block is a pointer, it can be modified directly, including the OC object, if not, it needs to be decorated with the __block keyword.
4, about reference counting
objects accessed in the block will default to retain:
UIImage * number; Number = [[UIImage alloc]init]; NSLog (@ "%ld", Cfgetretaincount ((__bridge cftyperef) number)); Block1 = ^ (int a,int b) {NSLog (@ "%ld", Cfgetretaincount ((__bridge cftyperef) number)); }; NSLog (@ "%ld", Cfgetretaincount ((__bridge cftyperef) number));
The results are as follows:
and the object adding __block will not be retain;
Note: If we access the member variables of the class, or access the object through a class method, the objects are not retain, and the class object is return, the most common self:
Typedef void (^myblock) (int,int) ; @interface ViewController2 () { myblock block1; __block uiimage * number; }@ end@implementation viewcontroller2-(void) Dealloc{ nslog (@ "dealloc %@", Self.class); nslog (@ "%ld", Cfgetretaincount ((__bridge cftyperef) number));} - (void) viewdidload { [super viewdidload]; self.view.backgroundcolor=[uicolor whitecolor]; number = [[uiimage Alloc]init] ; nslog (@ "%ld", Cfgetretaincount ((__bridge cftyperef) number)); block1 = ^ (int a,int b) { nslog (@ "%ld", Cfgetretaincount ((__bridge cftyperef) number)); }; //block1 (   &NB);Sp NSLog (@ "%ld", Cfgetretaincount ((__bridge cftyperef) number)); UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom]; btn.frame=cgrectmake (100, 100, 100, 100); btn.backgroundcolor=[uicolor redcolor]; [self.view addsubview:btn]; [btn addtarget:self action: @selector (click) forcontrolevents: UIControlEventTouchUpInside];} -(void) click{ [self dismissviewcontrolleranimated:yes completion:nil];}
Printing results:
As you can see, the UIImage object is not retain, and self also loops the reference, causing a memory leak. Here's how to fix it:
Number = [[UIImage alloc]init]; NSLog (@ "%ld", Cfgetretaincount ((__bridge cftyperef) number)); UIImage * im = number; Block1 = ^ (int a,int b) {NSLog (@ "%ld", Cfgetretaincount ((__bridge cftyperef) im)); }; NSLog (@ "%ld", Cfgetretaincount ((__bridge cftyperef) number));
Printing results:
Note: According to this mechanism, if we use the block for value, it must be set to nil when the block is not used, and it must be released in the method of implementing block, which we can explain by code:
First, create three viewcontroller for viewcontroller1,viewcontroller2,viewcontroller3;
1, create a button in viewcontroller1 , jump viewcontroller2
2, in viewcontrollerin 2:
#import "ViewController2.h" #import "ViewController3.h" @interface ViewController2 () { uibutton * im;} @end @implementation viewcontroller3-(void) Dealloc{ nslog (@ "dealloc %@", Self.class);} - (void) viewdidload { [super viewdidload]; uibutton * btn = [uibutton buttonwithtype:uibuttontypecustom]; btn.frame=cgrectmake (300, 300, 100, 100); btn.backgroundcolor=[ Uicolor redcolor]; [btn addtarget:self action: @selector (click) forcontrolevents:uicontroleventtouchupinside]; [self.view addsubview:btn]; im = [[uibutton alloc]initwithframe:cgrectmake (100, 100, 100, (+)];    IM.BACKGROUNDCOLOR=[UICOLOR BLACKCOLOR]; &NBSp; [im addtarget:self action: @selector (rele) forcontrolevents: Uicontroleventtouchupinside]; [self.view addsubview:im];} -(void) rele{ [self dismissviewcontrolleranimated:yes completion:nil];} -(void) Click{ viewcontroller3 * con = [[viewcontroller3 alloc] init]; [con setblock:^{ Im.backgroundcolor=[uicolor colorwithred:arc4random ()%255/255.0 green:arc4random ()%255/255.0 Blue:arc4random ()%255/255.0 alpha:1]; }]; [self Presentviewcontroller:con animated:yes completion:nil];}
3, in the ViewController3:
#import "ViewController3.h" void (^myblock); @implementation viewcontroller3-(void) Setblock: ( void (^) ()) block{ myblock = [block copy];} -(void) Dealloc{ nslog (@ "dealloc %@", Self.class);} - (void) viewdidload { [super viewdidload]; Self.view.backgroundcolor=[uicolor whitecolor]; myblock (); UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom]; btn.frame=cgrectmake (100, 100, 100, 100); btn.backgroundcolor=[uicolor redcolor]; [self.view addsubview:btn]; [btn addtarget:self action: @selector (click) forcontrolevents: UIControlEventTouchUpInside];} -(void) CLICK{    [SELF DISMISSVIEWCONTROLLERANIMATED:YES&NBsp;completion:nil];}
By printing the information, we will find that ViewController2 is not released because its member variable IM is not released in block retain, we do:
@interface ViewController2 () {UIButton * IM; ViewController3 * TEM;} -(void) rele{[tem setblock:nil]; [Self Dismissviewcontrolleranimated:yes completion:nil];} -(void) click{ViewController3 * con = [[ViewController2 alloc]init]; Tem=con; [Con setblock:^{im.backgroundcolor=[uicolor colorwithred:arc4random ()%255/255.0 green:arc4random ()%255/255.0 Blue: Arc4random ()%255/255.0 alpha:1]; }]; [Self Presentviewcontroller:con animated:yes completion:nil];}
This solves the memory problem.
Iv. Scope of The block
You should avoid using blocks in curly braces for the outside, and if necessary, you can declare the block as global.
Simple usage of block structure in IOS