IOS review notes 10: Use Block, ios review notes block
Function: saves a piece of code and can be executed at any time.
Flag: ^
Similar to functions:
1. Save a piece of code.
2 return values
3. Parameters
4. Call Method
Variable Declaration: function pointer variables are similar
Return Value Type (^ variable name) (parameter type list)
Typedef:
The block with the same return value and parameter can be of the same type as typedef.
Permission:
The block can access external variables;
However, by default, external local variables cannot be modified inside the block;
After the _ block keyword is added to the local variable, the variable can be modified within the block.
Example:
// Main. m # import <Foundation/Foundation. h> typedef int (^ MulBlock) (int, int); int main () {// define a block and assign the block Variable block1void (^ block1 )() = ^ {// if no parameters exist, you can omit the NSLog (@ "this is a block") ;}; // execute block1 (); int (^ addBlock) (int, int); addBlock = ^ (int a, int B) {return a + B;}; int (^ subBlock) (int, int )) = ^ (int a, int B) {return a-B ;}; NSLog (@ "% d + % d", addBlock (2, 1 ), subBlock (2-1); MulBlock add = ^ (int a, in B) {return a + B;}; MulBlock mul = ^ (int a, in B) {return a * B;}; return 0 ;}