When using blocks, why do you need __block for some variables, and for other variables, such as function parameters, you do not?
The question is really phrased in the wrong way. It's not "when do I need __block?", it's "what does __block do?". Once you understand what it does, you can tell when you need it.
Normally, when a block captures a variable (capturing occurs when a block references a variable outside itself), it creates a copy of the variable (note that in the case of objects it creates a copy of the pointer not the object itself), and if it's an object, retains it.
This means that with the normal behavior, you can't use a block to change a value outside the block. This code is invalid, for example:
int x = 5;
void(^block)() = ^{ x = 10; };
The __block qualifier makes two changes: most importantly, it tells the compiler that the block should capture it directly, rather than make a copy. That means you can update the value of variables outside the block. Less importantly, but still very relevantly, when not using ARC, it tells the compiler not to retain captured objects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With