Block basic concept block is a data type in OC is a working unit of code, can be executed at any time when needed is essentially a lightweight anonymous function, can be used as parameters of other functions or the return value block code itself may have a parameter list, There may also be a return value that assigns the block code to a variable and is called when needed, just like calling a normal function block code using the note by default, the value of the external variable is not allowed to be modified inside the block Code __block Circular Reference __weak format description: (return type) (^ Block name) (parameter type list) = ^ (formal parameter list) {Code implementation};void (^myblock) (int,int) = ^ (int x, int y) {//Code implementation}//The following is a simple use of the block #import < ; Foundation/foundation.h>typedef double (^myblock) (double, double); Myblock area = ^ (double x, double y) {return x * y;}; int a = 0;static int b = 11;/** block is defined */void test1 () {//block definition, is ready for a piece of code, execute when needed//block is C language format//input: INL Ineblock//Format: return type (^blockname) (parameter type) = ^ (formal parameter list) {code implementation}; Tip: If there are no parameters, the format can be simplified//format: return type (^blockname) () = ^ {Code implementation}; void (^myblock) () = ^{NSLog (@ "The simplest definition of block"); }; Call Myblock Myblock (); The most complete definition of int (^block) (int, int, int) = ^ (int x, int y, int z) {return x + y + z; }; int sum = 0; sum = block (10,19,20); NSLog (@ "sum-%d", sum); }/** external access variables, common interviewTitle 1*/void test2 () {int x = 10; __block int y = 20; NSLog (@ "x-%d, X-add-%p", x,&x); When a block is defined, if the block uses an external "local" variable, the block establishes a copy of the variable (the value of the current x is recorded) void (^block) () = ^{/********** when using a local variable, By default, the numeric value of the local variable is not allowed to be modified directly in block code ********///x = 20; /************ global variable can modify its value in block ******************/a = 10; /********** If you want to modify the value of an external variable in a block, you need to use __block***************/y = 30; NSLog (@ "block-x =%d", x); NSLog (@ "block-x =%p", &x); The default storage is in the stack}; Block (); NSLog (@ "Last X =%d", x); }/** external access variables, frequently meet questions 2*/void Test3 () {nsmutablestring *str = [nsmutablestring stringwithformat:@ "Hello"]; NSLog (@ "definition before-%p definition before-%p", &str, str); void (^block) () = ^{//Modifies the contents of the pointer to memory space [str setstring:@ "Water and Water"]; NSLog (@ "Block inside through pointer-%p%@", &str, str); }; Block ();} int main (int argc, const char * argv[]) {test3 (); return 0;}
Block of iOS