Objective-C study note _ Block
I. Block syntax
Block: Block syntax. It is essentially an anonymous function (a function without a name). Block variables are used to store functions. can Block variables be directly called? Function. There is no Block in Standard C, and the C language will be extended later, plus? Anonymous function. C ++, JS, Swift, etc ?, There are similar syntaxes called closures. The Block syntax is similar to the 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} the return value type can be omitted.
/ * Block type: int (^) (int, int)
* Block variable: block1
* Block value: ^ int (int x, int y) {return x + y;};
^ Return value type (parameter list) {function body} (return value type can be omitted)
* /
/ * 1. Block without return value, without parameters * /
void (^ block3) () = ^ ()
{
NSLog (@Hello, World!);
};
block3 (); / * Block call * /
/ * 2. No return value, with parameters * /
void (^ block4) (int, int) = ^ (int x, int y)
{
NSLog (@% d, x + y);
};
block4 (3, 45);
/ * 3. With return value, no parameters * /
int (^ block5) () = ^ ()
{
return 100;
};
NSLog (@% d, block5 ());
/ * 4. With return value, with parameters * /
int (^ block6) (int, int) = ^ (int x, int y)
{
return x> y? x: y;
};
NSLog (@% d, block6 (3, 5));
Ii. Block?
int (^ block1) (int x, int y) = ^ (int x, int y) {
return x + y;
};
int a = block1 (32, 34); // The use of block is similar to the use of function pointers
NSLog (@ “% d”, a); // print result: 66
Block? Typedef
Typedef int (^ BlockType) (int x, int y)
Original Type: int (^) (int x, int y)
New Type: BlockType
/* Block typedef */
typedef int(^blockType)(int, int);
blockType block1 = ^(int x, int y) {
return x + y;
};
NSLog(@%d, block1(3, 5));
Block writing
int (^block1)(int x, int y) = ^(int x, int y) {
return x + y;
};
BlockType block1 = ^(int x, int y) {
return x + y;
};
The above two implementations are equivalent.
Blcok and local variables and global variables
/ * Global variables defined outside the main function * /
int n = 100;
/ * Knowledge point 4 Block and local variables Global variables * /
/ * Local variables * /
int a = 100;
int (^ block) () = ^ () {
return a;
};
NSLog (@% d, block ());
int (^ block2) () = ^ () {
// a = 200;
return a;
};
/ * Summary: By default, blocks can access but cannot change local variables * /
__block int b = 200;
int (^ block3) () = ^ () {
b = 300;
return b;
};
NSLog (@% d, block3 ());
/ * Summary: Local variables decorated with __block, the value can be changed in Block * /
/ * Block and global variables * /
int (^ block4) () = ^ () {
n = 200;
return n;
};
NSLog (@n =% d, block4 ());
static int num = 1;
int (^ block5) () = ^ () {
num = 8;
return num;
};
NSLog (@num =% d, block5 ());