(a) Block
is a data type ( You need to define a variable to hold this type)
Function: Block (save) a piece of code, can be executed at any time
Block is like a function:
1. can save the code
2. there is a return value
3. tangible Parameters
4. call the same way
A block can be used as a function parameter or as a return value for a function, and it can have either an input parameter or a return value. In multi-threaded, asynchronous tasks, collection traversal, collection sorting, animation transitions with a lot of, therefore, Apple's official recommendation to try toMulti-use block。
(ii
) block definition
int (^mysum) (intint) = ^ (intint b) { return a +b;};
Defines a blocks object called MySum, which has two int parameters and returns an int. The right side of the equation is the concrete implementation of blocks
The block can access local variables, but cannot be modified.
int Ten ; int (^myblock) (int) = ^ (int num) { sum+ +; // Compile error return num * sum;}; // If you want to modify add Keyword: __blockint;
(iii) block and function pointer comparison> Defining function Pointers
Int (*MYFN) ();
> Definition Blocks
Int (^myblocks) (int,int);
> Calling Function pointers
(*MYFN) (10, 20);
> Call Blocks
Myblocks (10, 20);
(iv) Assignment of blocks
> Define a variable at the same time as the declaration, then assign a value
Int (^mysum) (int,int) = ^ (int a,int b) {
return a + B;
};
> can also first declare a type with a TypeDef, and then define the variable to assign the value
typedef int (^mysum) (int,int);
MySum sum = ^ (int a,int b) {
return a + B;
};
>block access to variables outside
code example
intA =Ten; __blockintb = -; void(^block) (); Block= ^{ //external variables can be accessed inside the block//NSLog (@ "a =%d", a); //by default, the outer local variables cannot be modified inside the block//a = 20; //Add the __block keyword to the local variable and the local variable can be modified inside the blockb = -; }; Block ();}
1>int (^sumblock) (intintvoid (^myblock) (); 2>^ (intint b) { return A- b;};
iOS development OC (13) Use of--block (1)