Like the closure in JS, anonymous functions in Java, C # delegates, you can pass Func as a parameter:
Statement of the 1.Block
The definition of block is similar to the declaration of a function, which is to change the function name to (^blockname). The following is the code for the block declaration.
With a return value.
int (^sumblock) (intint);
With no return value
void (^myblock) (intint);
2. Assign values to block blocks
Assign a value to the declared block. The value of the block is a function body, assigning a value to a block block in two ways, one at the time of Declaration, and one declared in the assignment.
Declare the re-assignment first
//Declaration of a code blockvoid(^myblock) (int,int); //assigning values to code blocksMyblock = ^ (intAintb) { //Test + +; //ErrorNSLog (@"Main_test =%d", test); //blockvar++ do not error;Blockvar + +; NSLog (@"Blockvar =%d", Blockvar); intsum = a +b; NSLog (@"A + b =%d", sum);};
Assigning values at the time of declaration
int (^sumblock) (intint) = ^ (intint b) { int sum = a + b; return sum;};
3. Call Block
The use of the block is the same as the normal function, and the method is called as follows:
// Call the code block and receive the return value int sum = sumblock (+);
4. Pass the block as a parameter to the function
// use code blocks as function arguments void blockfunction (int (^myblock) (intint)) { int sum = Myblock (ten); NSLog (@ "fun_sum =%d", sum);}
5. Using local variables and global variables in code blocks
We can access and modify the global variables in the block, but we can only access the local variables, and if we want to modify them, we can add the keyword __block when we declare the local variables.
The code is as follows
int 0;
Simple understanding of block in objective-c