Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will ARC tell me when I must use __block?

AFAIK, __block is used when you're changing, inside the block, the address that a variable (declared outside the block) points to.

But, what if I'm changing the value that the variable points to but the pointer stays the same? E.g., what if I have NSMutableArray *array and am just doing [array addObject:object] inside the block? In this case, I'm not changing the pointer array, but I'm changing the value it points to. So, must I still use __block in declaring NSMutableArray *array?

like image 767
ma11hew28 Avatar asked Sep 16 '11 01:09

ma11hew28


1 Answers

You only need __block if you are changing the value of the variable.

I.e. if you have:

NSArray* foo;

You only need __block if you change the value of foo. Now, keep in mind that foo is nothing more than "a pointer to a thing that is typed NSArray". I.e. foo is effectively a 64 bit or 32 bit integer, depending on platform. If you change that integer, you need __block. If you don't, you don't need __block.

So, no, you don't need __block to call addObject: on the array since you aren't actually changing the value of foo.

If you were to do something like foo = (expression);, then you'd need __block.

(note that this is one of the reasons why concurrent programming under OO is so damned hard... it is exceptionally hard to define the "domain of variance" for any given execution path)

like image 90
bbum Avatar answered Oct 11 '22 19:10

bbum