IOS learning-9, ios-9
A video from Jay Chou.
Block is used to save a piece of code.
Block flag: ^
Blocks are similar to functions.:
1 ).Code can be saved2 ).Return Value3 ).Parameter
Temp1: Block without return values or parameters
If the block does not have a form parameter, You can omit ()
Void (^ myblock) () = ^ {NSLog (@ "----------"); NSLog (@"----------");}; // call the internal code myblock () of the block using the block variable ();
Temp2: Return Value and Parameter
Int (^ sumblock) (int, int) = ^ (int a, int B) {return a + B ;}; // return value int c = sumblock ); NSLog (@ "% d", c );
Temp3: Use a block to output n horizontal lines.
Void (^ lineblock) (int) = ^ (int n) {for (int I = 1; I <n; I ++) {NSLog (@ "-------") ;}; // No return value. Add the lineblock (5) parameter of the int type );
Temp 4:
_ Block int a = 10; void (^ block) (); block = ^ {/* block can access external variables by default, you cannot add the _ block keyword to the local variable within the block. You can modify this local variable within the block */a = 20; NSLog (@ "% d ", a) ;}; block ();
Temp 5: Use typedef to define the block type
// Type + variable MyBlock sumBlock; sumBlock = ^ (int a, int B) {return a + B ;}; sumBlock (10, 9); // subtract MyBlock minusBlock; minusBlock = ^ (int a, int B) {return a-B ;}; minusBlock (10, 9); // multiply MyBlock multipBlock; multipBlock = ^ (int a, int B) {return a * B;}; multipBlock (); // division MyBlock divideBlock; divideBlock = ^ (int a, int B) {return a/B ;}; divideBlock (); NSLog (@ "\ n % d", sumBlock (), minusBlock ), multipBlock (10, 9), divideBlock (10, 2 ));
Summary:
1. How to define block Variables
int (^sumBlock)(int,int);void (^myBlock)();
2. How to Use block to encapsulate code
^ (Int a, int B) {return a-B ;}; // No parameter ^ () {NSLog (@"-----");} // No return value ^ {NSLog (@"-----");}
3. block access to external variables
1. The block can access external variables. 2. By default, the block cannot modify external local variables.
3. Add the _ block keyword to the local variable. This local variable can be modified within the block.
4. Use typedef to define the block type
Typedef int (^ MyBlock) (int, int); // you can use MyBlock to define the block Variable MyBlock block; MyBlock b1, b2; b1 = ^ (int, int B) {return a + B ;}; MyBlock b3 = ^ (int a, int B) {return a + B ;};