Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When and when not to use __block in Objective-C? [closed]

When using blocks, why do you need __block for some variables, and for other variables, such as function parameters, you do not?

like image 769
Josh Sklar Avatar asked Feb 07 '13 19:02

Josh Sklar


1 Answers

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.

like image 111
Catfish_Man Avatar answered Oct 28 '22 23:10

Catfish_Man