According to the storage domain of Block, they can be divided into three categories:
1.NSGlobalBlock global area (the data area of a program)
2.NSStackBlock stack area (only in MRC), beyond the scope of variables on the stack, Block and __block type variables have been destroyed.
3.NSMallocBlock heap region, the variable is not affected at the end of the scope of the variable
So what kind of Block do we usually create?
To summarize, generate the block in the global zone:
When 1. definition of global variables in the block grammar
Do not use automatic variable intercept expression 2.block syntax in the
The rest of the block is the stack area Block., so what’s the Block of the heap area?
In fact, in general ARC opened, created in the stack area Block will be copied to the heap area (system), to prevent out of scope after the block variable will be destroyed and can not be used normally. In general, under the following circumstances, the Block stack will be copied to the heap area:
1. call the copy instance method of Block (ARC automatically calls), or the Block_copy method
2.Block returns value as a function
3. assigns the value of Block to the __strong modified ID type or the Block type member variable
4. when passing the Block in the Cocoa framework of the method containing usingBlock or in the GCD of the API
In MRC case, Block copies from stack to heap:
Block_copy (block body), in order to avoid memory leaks, Block_copy must be used in conjunction with Block_release (block)
At the same time, the Foundation framework provides two methods that work in the same way as the above functions:
Block = [block copy]; [block release] (ARC automatic replication is to call the copy method)
The local variables used in Block syntax expressions are appended as member variables to the structure in which Block is located, so that the local variables (the underlying data type) cannot be modified;
When a local variable is decorated with __block, its address is appended as a member variable to the structure in which Block is located, so that the local variable can be modified