Block is a data type that is used to store code--to hold a piece of code, to call it when you want to use code
Usage scenarios:
1. Animations
2. Multithreading
3. Collection traversal
4. Network Request callback
Difference from function:
A function is also used to hold a piece of code, and the code is executed when the function is called.
However, the function cannot execute the code at the specified location while the program is running.
1. Block with no parameters and no return value
void (^GM) () = ^{nslog (@ "...");}; The GM is the variable name of the block variable, which is used to save this section of code {NSLOG (@ "...");}
GM (); Execute block Code
2. Block with parameters that do not return a value
void (^GM) (int) = ^ (int count) {for (int i = 0; i < count; i++) NSLog (@ "...");};/ /print the specified number of lines ...
GM (5);
3. Block with parameters and return values
Int (^sum) (int, int) = ^ (int a, int b) {return a+b;};/ /ask for two number of a and
int c = SUM (2,3);
typedef
typedef old New;//used to simplify the name of the type. Use typedef to define an alias for the type of block;
1. typedef int (^myblock) (int, int); Myblock <=> Int (^) (int, int);
2. Myblock minus = ^ (int a,int b) {return a-C};
equivalent to (int) (^minus) (int, int) = ^ (int a,int b) {renturn-A;};
Usage Scenarios for block:
When the code of a function is the same as the code behind it, the code in the middle is different. You can encapsulate the middle code as a block of code, as a function parameter. Each time the function is called, the code is dynamically passed in.
Block cannot pass null nil and will cause bad access. Need to add judgment.
void Gotwork (void (^work))
{
NSLog (@ "Begin");
if (work! = nil)//**
{
Work ();
}
NSLog (@ "End");
}
Block calls external variables:
1. Block can access external variables
2. By default, the block cannot modify the outside local variables
If you want to modify an external variable before adding __block
Use of the IOS Block