Description of block :
Block is a new syntax structure after iOS4.0, also known as "Closure (closure)".
SDK4.0 's new API uses blocks heavily.
Block is an anonymous function code block that can be passed as a parameter to other objects.
Object
Method
Block Blocks {
... Code
};
}
use of block:Statement of the 1.block
Defining types, defining variables
Int (^sum) (int a, int b);
creation of 2.block
Implement block
sum = ^ (int a, int b) {
return a+b;
};
3.block of Calls
1 Direct call
int sum1 = ^ (int a,int b) {
return a+b;
} (5,9);
NSLog (@ "%d", sum1);
2 called by the block variable
int sum2 = SUM (20,39);
NSLog (@ "%d", sum2);
4. Block in many cases#pragma Mark Creatkindsofblock
-(void) creatkindsofblock{
1---No parameter, no return value
^(){
NSLog (@ "No parameter, no return value");
}();
2---with parameters, no return value
^ (int a,nsstring *text) {
NSLog (@ "%d,%@", a,text);
} (88,@ "parameter, no return value");
3---No parameters, with return value
NSString *text = ^ () {
return @ "has a return value, no parameters";
}();
NSLog (@ "%@", text);
4---with parameters, return value
}
5. Global block Variables
First, define a global block
{
Int (^myblock) (int a, int b);
}
#pragma mark-Global block variable
-(void) createmyblock{
Defining a block variable
Int (^sumblock) (int x,int y);
Implement block, and assign values
Sumblock = ^ (int x,int y) {
return x+y;
};
Direct assignment, the block variable can be directly assigned to the value
Myblock = Sumblock;
}
Global block can be directly called, directly assigned value
Global block variable
[Self createmyblock];
NSLog (@ "sum:%d", Myblock (20,60));
Of course, the initial understanding of block should also have block application scenarios, blocks and variables, block memory management Some problems, I will not write??。 Because I am a small rookie ~, so, I have to write homework to do exercises, trouble everyone do not spit groove, much encouragement, thank you. Hope to and I just started learning iOS classmates have a little help, summed up is not very good, if there are errors, please correct me, I will humbly learn from you.
The first knowledge of block