Block in OC, OCBlock
Block encapsulates a piece of code that can be executed at any time
A Block can be used as a function parameter or return value, and it can contain an input parameter or return value.
Apple officially recommends using block as much as possible. It is widely used in multithreading, asynchronous tasks, set traversal, set sorting, and animation transfer.
I. Definition of Blocks:
Int (^ MySum) (int, int) = ^ (int a, int B ){
Return a + B;
};
Defines a blocks object named MySum. It has two int parameters and returns int. The right side of the equation is the specific implementation of blocks.
Block can access local variables, but cannot be modified.
Int sum = 10;
Int (^ MyBlock) (int) = ^ (int num ){
Sum ++; // compilation Error
Return num * sum;
};
If you want to modify it, add the keyword :__ block.
_ Block int sum = 10;
Ii. Define function pointers
Int (* myFn )();
Define Blocks
Int (^ MyBlocks) (int, int );
Call function pointer
(* MyFn) (10, 20 );
Call Blocks
MyBlocks (10, 20 );
3. Define variables while declaring and assign values
Int (^ MySum) (int, int) = ^ (int a, int B ){
Return a + B;
};
You can also declare the type first with typedef and then define the variable to assign values.
Typedef int (^ MySum) (int, int );
MySum sum = ^ (int a, int B ){
Return a + B;
};