define block variable
int (^myBlock)(int ,int );
normal code block
{ do something... member variables in a code block are scoped to the end of the code block }
block encapsulates a block of code
A block encapsulates a piece of code that can be called at any time. Much like functions, you can save code and have parameters and return values.
^(){ }; ^{ }; ^(int a ,int b){ };
The definition + encapsulation is as follows, the sign of the block: ^
void (^blockName)()=^{//If the block has no formal parameters, you can omit ^() do something... };
Use block to call block internal code
blockName();
block with parameter return value
int (^blockName)(int a,int b)=^(int a ,int b){ do something... return a+b; }; int c = blockName(1,2);
Similar to pointer functions in C
int sum(int a ,int b) { return a+b; } int (*p)(int, int) = sum(); int c = p(1+2);
block member variable scope
int a = 1; __block int b = 2; void (^blockName)(); blockName = ^{ //1, inside the block can access external variables //2. By default, block cannot modify external local variables such as a= 2; //3. If you want to modify external variables, you need to add __block (two underscores) such as b = 1; }; blockName();
typedef definition block
//typedef defines function pointer typedef int (*P)(int, int); int sum(int a ,int b) { return a+b; } P p1 = sum P p2 = sum;
in the same block
typedef (^BlockName)(int, int);//Define the type, you can use the BlockName type to define block variables in the future BlockName sumBlock; sumBlock = ^(int a ,int b){ return a + b; }; BlockName minusBlock = ^(int a ,int b){ return a - b; };