In iOS, blocks is an object, which encapsulatesCodeThis code can be executed at any time. Blocks can be used as a function parameter or return value, and it can include an input parameter or return value. It is similar to the traditional function pointer, but there is a difference: blocks is inline and it is read-only for local variables.
Blocks definition:
INT (^ multiply) (INT, INT) = ^ (INT num1, int num2) {return num1 * num2 ;};
Defines a multiply blocks object. It has two int parameters and returns an int. The right side of the equation is the specific implementation of blocks. Note the {} blocks body ;.
Blocks can access local variables but cannot be modified.
Int multiplier = 7;
INT (^ myblock) (INT) = ^ (INT num ){
Multiplier ++; // compilation Error
Return num * multiplier;
};
If you want to modify it, add the keyword :__ block.
_ Block int multiplier = 7;
INT (^ myblock) (INT) = ^ (INT num ){
Multiplier ++; //.
Return num * multiplier;
};
...
In the reference counting environmentBlockReferenceObjective-CObject time
Wait, the object will beRetain. When you reference an instance variable of an object, it is also retain.
But the object variables marked by the _ block storage type modifier will not beRetain.
Note: In the garbage collection mechanism, if you use both _ weak and _ block to identify a variable, the block
It will not always be valid.
If you useBlock, the memory management rules of objects are more subtle:
If you access an instance variable through reference, self will beRetain.
If you access an instance variable through the value, the variable will beRetain.
Dispatch_async (queue, ^ { |
// Instancevariable is used by reference, self is retained |
Dosomethingwithobject (instancevariable ); |
| });
|
| |
| |
Id localvariable = instancevariable; |
Dispatch_async (queue, ^ { |
| // Localvariable is used by value, localvariable is retained (not self)
|
Dosomethingwithobject (localvariable ); |
| });
|
Copy Blocks
Generally, you do not needCopy (or retain) a block.In the declared scope
If it is used after destruction, you need to make a copy. Copy will move the block to the heap.
You can use the c FunctionCopyAndReleaseOneBlock:
If you useObjective-C, you can give a blockSendCopy and retainAndRelease (or
Autorelease) message.
To avoid Memory leakage, you must always balanceBlock_copy () and block_release (). You must balance
CopyOrRetainAndRelease (or autorelease) -- unless it is in a garbage collection environment.