Objetive-C learning _ Block learning notes, objetive-c_block
Block: an anonymous function with an automatic variable (local variable.
Block: used to save a piece of code and can be called when appropriate.
Block essence: struct, which contains a function pointer
Block application scenarios: animation, multithreading, set traversal, and network request callback
Block format: ^ return value type parameter list {expression} (this parameter can be omitted if the return value type is void and the parameter list is empty)
Comparison between Block and function:
Declared function type: int (* funcptr) (int );
Declare Block type: int (^ blk) (int );
The function uses typedef: typedef int (^ blk_t) (int), and blk_t is used directly.
Block uses typedef: typedef int (* funcptr) (int); when assigning values, use the function address funcptr func = & addTen;
Example: blk_t blt = ^ int (int a) {// the return value is generally not written. The parameter list must have ()
Return 4;
};
Intercept automatic variable value: Block intercepts the value of the used automatic variable. If it is not used, it will not be intercepted. That is, the instantaneous value of the automatic variable is saved. After the Block syntax is executed, even if the value of the automatic variable used in the Block is rewritten, the value of the automatic variable during Block execution is not affected.
Code:
(1) int a = 10;
Blk_t block = ^ {
NSLog (@ "% d", );
};
A = 100;
Block (); // The printed result is 10 rather than 100.
(2) Person * p = [[Person alloc] init];
P. name = @ "James ";
Blk_t block = ^ {
// Get the address, not the object itself
NSLog (@ "% @", p. name );
[P1 release];
};
P. name = @ "Li Si ";
[P release];
P = nil;
Block ();
} // [Person name]: message sent to deallocated instance 0x100300170
Knowledge points and notes:
(1) by default, block cannot modify the external local variables (basic data type), unless _ Block is added before
(2) The local variables used in the Block syntax expression are appended to the struct where the Block is located as member variables.
(3) The Block can be used as a function parameter. It must be determined before calling the Block. The Block can be nil.
(4) It is best to use typedef when using Block.
(5) If you get a reference, you can modify the attributes of the object. You can also modify it without adding _ Block.
(6) using retain in a block seems to be ineffective, but using release is acceptable.