First, block syntax
Blocks: Block syntax, which is essentially an anonymous function (a function without a name), the implementation of the block variable holding function, which can be directly adjusted by the block variable. There is no post-extended version of Block,c language in standard C, plus anonymous functions. C + +, JS, swift and other language, there is a similar syntax, called closures. The block syntax is similar to a function pointer.
- Block type: Int (^) (int)
- Block variable: myblock
- Block value: ^ int (int num) {return 7 * NUM;}
- That is: ^ return value type (parameter list) {function Body} where the return value type can be omitted.
/ * block type: Int (^) (int, int) * block variable: BLOCK1 * Block's value: ^int (int x, int y) {return x + y;}; ^ return value type (parameter list) {function Body} (The return value type can be omitted) */ / * 1. No return value, no parameter of block * / void(^BLOCK3) () = ^() {NSLog(@"Hello, world!."); }; Block3 ();/ * Block call * / / * 2. No return value, parameter * / void(^BLOCK4) (int,int) = ^(intXintY) {NSLog(@"%d", x + y); }; Block4 (3, $);/ * 3. There is a return value, no parameter * / int(^BLOCK5) () = ^() {return -; };NSLog(@"%d", Block5 ());/ * 4. There are return values, parameters * / int(^BLOCK6) (int,int) = ^(intXintY) {returnx > y? x:y; };NSLog(@"%d", Block6 (3,5));
Second, block to make?
int (^block1)(intint y) = ^(intint y) { return x + y;};int a = block1(3234); // block的使?和函数指针的使用类似NSLog(@“%d”, a); // 打印结果:66
Block into the typedef.
typedef int (^BLOCKTYPE) (int x, int y)
Primitive type: Int (^) (int x, int y)
New Type: Blocktype
/* Block typedef */typedefint(^blockType)(intint);blockType block1 = ^(intint y) { return x + y; };NSLog(@"%d", block1(35));
Block notation
int (^block1)(intint y) = ^(intint y) { return x + y;};
BlockType block1 = ^(intint y) { return x + y;};
The above two implementations are equivalent.
Blcok and local variables and global variables
/ * global variable defined outside the main function * / intn = -;/* Knowledge point 4 block vs. local variable global variable */ / * Local variable * / intA = -;int(^block) () = ^() {returnA };NSLog(@"%d", block ());int(^BLOCK2) () = ^() {//A = $; returnA };/* Summary: By default, block can access but cannot change local variables */__blockintb = $;int(^BLOCK3) () = ^ () {b = -;returnb };NSLog(@"%d", Block3 ());/* Summary: Using __block modified local variables, block inside can change the value */ /* Block and global variables */ int(^BLOCK4) () = ^ () {n = $;returnN };NSLog(@"n =%d", Block4 ());Static intnum =1;int(^BLOCK5) () = ^ () {num =8;returnNum };NSLog(@"num =%d", Block5 ());
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
OBJECTIVE-C Study Notes _block