1. Block action:
Block is used to encapsulate 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.
- Apple's official proposal to use block as much as possible. In multi-threaded, asynchronous tasks, collection traversal, collection sorting, animation transitions with a lot of
2. Definition of BLOCK:
int (^MySum)(intint) = ^(intint b) { return a+b; };
As the above code defines a blocks object called MySum, it has two int parameters and returns an int. The right side of the equation is the concrete implementation of blocks
Block can access local variables, but cannot modify:
intsum10;?int (^MyBlock)(int) = ^(int num) { sum++;//编译报错 returnsum; };
Add keywords If you want to modify:
__block __block int sum = 10;
-
Defines the function pointer int (*MYFN) ();
Call function pointer (*MYFN) (10, 20)
-
Definition Blockint (^myblocks) (int,int);
Call Blocks Myblocks (10, 20);
-
Define the variable at the same time as the declaration, then assign the value
int (^MySum)(int,int) = ^(int a,int b) { return a + b;};
D. You can also first declare the type with a TypeDef, and then define the variable to assign the value
typedefint (^MySum)(int,int);MySum sum = ^(int a,int b) { return a + b;};
3. Block access to external variables
- External variables can be accessed within the block;
- By default, the outer local variables cannot be modified inside the block;
- Add the keyword _block to the local variable, and the local variable can be modified inside the block;
NetEase Interview Questions:
When does 13.__block use
14. Inside the block, add operations to the array, which need to be declared as __block?
15. Inside the block, modify the Nsinteger, whether the Nsinteger needs to be declared as __blcok
Go to IOS development-block usage explained