Block
- Block encapsulates a piece of code that can be executed at any time
- A block can be used as a function parameter or as a return value for a function, and it can have either an input parameter or a return value. It is similar to a traditional function pointer, but there is a difference: block is inline (inline), and by default it is read-only to local variables
- Apple's official proposal to use block as much as possible. In multi-threaded, asynchronous tasks, collection traversal. Collection sort. Animation transitions with a lot of
Block definition: Int (^mysum) (int,int) = ^ (int a,int b) {return a+b;}; Defines a block object called MySum, which has two int parameters and returns an int. The right side of the equation is the concrete implementation of block, which can access local variables, but cannot be modified. int sum =10;int (^myblock) (int) = ^ (int num) {sum++;//compile error return num*sum;}; Add keyword if you want to modify: __block (
Two slide lines before block ) For example: (__block int sum=10;) In addition, we can define blocks with TypeDef, for example:
int (^mysum) (int A,int b) void Test () { // declares a block variable mysun sum=^ (int A,int b) { return A +b; } NSLog (@ "%i", SUM (ten+))}
The block can access local variables, which are read-only by default and cannot be modified, for example:
void test2 () { // define a variable c int c=1outside the block; Mysum sum=^ (int A,int b) { // Print the outer c inside the block NSLog (@ "%i", c); return A +b; } NSLog (@ "%i", sum (ten);}
If you want to modify, you need to add __block keyword, block before is two underscores using block to do the listener, example:
// main.m File void Test () { *btn=[[Button alloc] init]; Btn.block=^ (Button *btn) { NSLog (@ "buttons are clicked"); } [BTN click];}
Button.h file
@class Button; // defines a block that passes a parameter of type button void (^buttonblock) (Button *btn); @property (nonatomic, assign) Buttonblock block; -(void) click;
BUTTON.M file
-(void) click{ _block (self);}
The pointer to the function is different from the block:
int (^sum) (int,int) =^ ( int A,int b) { return a +b;}; // Block
int (*sum) (int,int) =sum; int sum (int A,intreturn +b;} // function
OC----block Syntax