Video from Li Mingjie.
Block is used to save a piece of code
Block's logo: ^
block is like a function :
1). Can save code 2). Has a return value of 3). Tangible parameters
Temp1: Block with no return value, no formal parameters
If the block has no formal parameters, you can omit ()
void (^myblock) () = ^{ NSLog (@ "----------"); NSLog (@ "----------"); }; // use block variables to invoke code inside block Myblock ();
Temp2: There are return values, tangible parameters
int (^sumblock) (int,int) = ^ (int A,int b) { return a +b; } ; // return value int c = sumblock (1,1); NSLog (@ "%d", c);
Temp 3: Output n horizontal lines with a block
void (^lineblock) (int) = ^ (int n) { for (int1; i < n; i++) { NSLog ( @"-------"); } }; // no return value, plus argument of type int Lineblock (5);
Temp 4:
__block int a = 10 void (^block) (); Block = ^{ /* inside the block can access the variables outside by default, the block inside cannot modify the outside local variables to the local variable plus the __block keyword, this local variable can be modified within the block */ a = ; NSLog ( @ " %d " ,a); }; Block ();
Temp 5: defining block types with typedef
//type + variableMyblock Sumblock; Sumblock= ^(intAintb) { returnA +b; }; Sumblock (Ten,9); //SubtractionMyblock Minusblock; Minusblock= ^(intAintb) { returnAb; }; Minusblock (Ten,9); //multiplicationMyblock Multipblock; Multipblock= ^(intAintb) { returnAb; }; Multipblock (Ten,9); //DivisionMyblock Divideblock; Divideblock= ^(intAintb) { returnAb; }; Divideblock (Ten,2); NSLog (@"\ n%d \ n%d \n%d \ n%d", Sumblock (Ten,9), Minusblock (Ten,9), Multipblock (Ten,9), Divideblock (Ten,2));
Summarize:
1. How to define a block variable
int (^sumblock) (int,int); void (^myblock) ();
2. How to use block encapsulation code
^ (int A,int b) { return A- b; }; // No parameters ^() { NSLog (@ "-----"); } // no return value ^{ NSLog (@ "-----"); }
3. Block access outside variables
1.block internal can access the outside of the variable 2. By default, the outer local variables cannot be modified inside the block
3. Add the __block keyword to the local variable and the local variable can be modified inside the block
4. Defining block types with typedef
int (^myblock) (int,int); // You can then use this type of Myblock to define the block variable Myblock block; Myblock b1,b2; = ^ (int A,int b) { return a +b; } ; = ^ (int A,int b) { return a +B; };
iOS Learning-9-1. Block Getting Started