Difference between _ Block and _ Weak, __block _ Weak
I. Blocks comprehension:
Blocks can access local variables, but cannot be modified,
When block is declared, another temporary variable is copied,
Even if the copied variables are modified in the block, the original variables outside the block are not affected. The so-called closure.
If you modify a local variable, add _ block.
The API Reference provides the following explanations for the _ block Variable modifier:
//A powerful feature of blocks is that they can modify variables in the same lexical scope. You signal that a block can modify a variable using the __block storage type modifier. //At function level are __block variables. These are mutable within the block (and the enclosing scope) and are preserved if any referencing block is copied to the heap.
The general meaning is two points:
1. The _ block object can be modified and assigned a value again in the block.
2. The _ block object will not be strongly referenced by the block once, so as to avoid the issue of circular reference.
Ii. _ weak
_ Weak _ typeof (& * self) weakSelf = self; equivalent
_ Weak UIViewController * weakSelf = self;
Why not use the _ block parameter because the instance variables of self are accessed through reference. self is retain and the block is also a strong reference,
It causes loop reference. The _ week is a weak reference. When self is released, weakSelf is equal to nil.
The API Reference describes the modifier of the _ weak variable in the following ways:
__weak specifies a reference that does not keep the referenced object alive. A weak reference is set to nil whenthere are no strong references to the object.
An object with the _ weak modifier is equivalent to a property defined as weak. Naturally, circular references will not be caused, because the apple documentation already makes it clear that when the original object does not have any strong references, the weak reference pointer will also be set to nil.
Therefore, the difference between the _ block modifier and the _ weak modifier is quite obvious:
1. _ block can be used in both ARC and MRC modes. Objects and basic data types can be modified.
2. _ weak can only be used in ARC mode, and only objects (NSString, etc.) can be modified. Basic data types (int) cannot be modified ).
3. The _ block object can be assigned a value again in the block, __weak is not allowed.
The PS :__ unsafe_unretained modifier can be regarded as a substitute for _ weak in iOS SDK 4.3 or earlier versions, but it will not be automatically set to nil. So try not to use this modifier.