I'm reading Xcode's documentation, and here is something that puzzles me:
__block typeof(self) tmpSelf = self;
[self methodThatTakesABlock:^ {
[tmpSelf doSomething];
}];
The following is copied from the documentation:
A block forms a strong reference to variables it captures. If you use
self
within a block, the block forms a strong reference toself
, so if
self
also has a strong reference to the block (which it typically
does), a strong reference cycle results. To avoid the cycle, you need
to create a weak (or__block
) reference to self outside the block, as
in the example above.
I don't understand what does 'a weak (or __block
)' mean?
Is
__block typeof(self) tmpSelf = self;
and
__weak typeof(self) tmpSelf = self;
exactly the same here?
I found another piece in the document:
Note: In a garbage-collected environment, if you apply both
__weak
and
__block
modifiers to a variable, then the block will not ensure that it is kept alive.
So, I'm totally puzzled.
Best Answer
From the docs about __block
From the docs about __weak
So they are technically different things. __block is to stop your variable being copied from your external scope into your block scope. __weak is a self delimiting weak pointer.
Note I said technically, because for your case they will do (almost) the same thing. The only difference is if you are using ARC or not. If your project uses ARC and is only for iOS4.3 and above, use __weak. It ensures the reference is set to nil if the global scope reference is releases somehow. If your project doesn't use ARC or is for older OS versions, use __block.
There is a subtle difference here, make sure you understand it.
EDIT: Another piece to the puzzle is __unsafe_unretained. This modifier is almost the same as __weak but for pre 4.3 runtime environments. HOWEVER, it is not set to nil and can leave you with hanging pointers.