A: basic definition
/* Some understanding and explanations of the initial block definition are explained below:
*block named Myblock, combined with the C function pointer, Myblock as a block body pointer, pointing to the block body's entry address
*int result = Myblock (5) <==> ^ (int num) {return num*num} (5)//pass 5 to Num
* Myblock can be passed as a parameter in callback, or it can be passed directly into block body ^ (int num) {...};//
* When the entire block body is passed in as a parameter, there are often no parameters, just a delay operation, because the block content is defined
The block is not executed if it is not needed for a temporary lvalue.
Example: [Request Setfailedblock:^{nserror *error = [request error];};
If the Setfailedblock method is not executed, the latter block is not executed, but is quietly in the heap, the principle will be said next.
*/
Two: block principle
First introduce the basic block, the OC language block into the C language block
Specific steps:
We can see through the IMP definition:
In the main () function, the return value of the Block is (void (*) ()), which is actually a function pointer, in which case the block can be treated as a function pointer to an anonymous function.
Three: Keyword __block
Main function: 1.block to external variables is read-only, to become readable writable, you need to add __block
2. Copy the block from the stack onto the heap to avoid a circular reference to the situation
Block with __block keyword for oc->c language conversion:
Four: Storage type
There are three types of block storage: _nsconcretstackblock (Stack), _nsconcretglobalblock (Global), _nsconcretmallocblock (heap)
Point one: The block is stored on the stack when it is inside the function and defines it using variables inside the function.
Point two: when the block is defined outside the function body, or defined inside the function body, and when the function executes, the block body does not need to use the internal variables inside the function, The block will be stored as a global block when the function is executed and the content is defined without using the function body.
key Three: the global block is stored in the heap, and the copy operation on the global block returns the original function pointer, and the copy operation on the block in the stack produces two different block addresses, which is the entry address of the two anonymous functions.
Point four: The ARC mechanism optimization will call the block of the stack to the block of heap.
The following storage class topics are excerpted from the Cocoachina forum:
iOS Development-Grammar Chapter-block detailed