Some Understanding about block itself in OC (1), ocblock understanding
1. block
1. block: save a piece of code.
2. A syntax officially recommended by Apple. It is similar to a C-language function, but it is more flexible than a function.
3. ^ indicates the block syntax.
Ii. block usage
1) No return value, no Parameter
1-(void) myFirstBlock 2 {3 // 1. define block 4 void (^ myblock) () = ^ {5 NSLog (@ "No parameter no return value"); 6}; 7 // 2. call block 8 myblock (); 9 10}
Output result:
09:56:50. 124 01-block [750: 25107] No parameter no return value
2) parameters with no return values
-(Void) mySecondBlock {// 1. define block void (^ mySecondBlock) (int, int) = ^ (int num1, int num2) {NSLog (@ "parameter has no return value: % d ", num1 + num2) ;}; // 2. call block mySecondBlock (2, 3 );}
Output result:
10:03:22. 221 01-block [811: 30160] parameters with no return value: 5
3) parameters with return values
1-(void) myThirdBlock 2 {3 // 1. define block 4 double (^ myThirdBlock) (double, double) = ^ (double r1, double r2) {5 return r1 + r2; 6}; 7 // 2. call block 8 double r3 = myThirdBlock (1.1, 2.2); 9 NSLog (@ "parameters with returned values: % f", r3); 10}
Output result:
10:06:42. 615 01-block [861: 32505] parameters with return values: 3.300000
Iii. block syntax format
4. block attention
1) The Block can access external variables;
2) by default, external local variables cannot be modified inside the Block.
3) Add the _ block keyword to the local variable. Then, the local variable can be modified within the block.
The sample code is as follows:
1 - (void)myFourBlock2 {3 int num = 5;4 void (^myFourBlock)() = ^{5 6 num = 6;7 NSLog(@"%d",num);8 };9 }
If the code above is written, Xcode will report the error "missing _ block type specifier;" in the sixth line "num = 6;
The modification code is as follows:
- (void)myFourBlock{ __block int num = 5; void (^myFourBlock)() = ^{ num = 6; NSLog(@"%d",num); }; myFourBlock();}
Output result:
2016-02-18 10:25:02.195 01-block[1016:45943] 6
Code abuse me a thousand times, and I am waiting for code like my first love!