Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative syntax to __block?

I have question on the syntax of __block variables. I know you can use __block on a variable in scope so it's not read-only inside the block. However in one spot in the apple docs, I saw an alternative:

"Variables in the defining scope are read-only by default when used in a block. If you need to change the value of such a variable, you can use a special syntax:

int count = 0; float cumulativeValue = 0.0; UpdateElements( a, N, ^(float element){     |count, cumulativeValue|     float value = factor * element;     ++count;     cumulativeValue += value;     return value; } ); 

In this example, count and cumulativeValue are modified inside the block, so they are included in comma-separated list of shared variables at the beginning of the block scope.

This syntax seems much cleaner and I assume you could then modify variables you did not declare but are still in scope. However, I haven't seen this anywhere else and the xCode compiler does not like my basic block. Is this legitimate syntax?

like image 539
pk-nb Avatar asked Jun 07 '13 16:06

pk-nb


People also ask

What does __ block mean in Objective C?

__block is a storage qualifier that can be used in two ways: Marks that a variable lives in a storage that is shared between the lexical scope of the original variable and any blocks declared within that scope.


2 Answers

Wow. Haven't seen that syntax in a long time.

That was one of the various syntactic structures explored during the development of blocks. It was eventually rejected because it was too imprecise in declaring intent and the resulting behavior would have been confusing.

Consider a scope with three blocks, two of which declare a variable as readwrite via |a|. There would be no way of knowing from the int a = 5; declaration at the top of the scope that the variable's value is readwrite in some of the block's scope.

As well, it would make the compiler implementation significantly more difficult. The tradition in C is that a variables storage type is fixed at the time of declaration. Supporting this syntax would have broken that expectation.

Thus, it was decided to use a storage type modifier akin to volatile or static. __block was used primarily because the __ prefix greatly reduces the amount of code that would break by adding a bare keyword.

Thanks for asking this. Bug filed and that documentation will be fixed and/or removed eventually.

like image 112
bbum Avatar answered Sep 19 '22 19:09

bbum


The | | syntax was inspired by Smalltalk, as was, of course, the term "block".

As bbum points out, marking the decl site is more honest w.r.t. non-block usage and far more in line with C when modeled, as it ended up, as a new (C) object "duration".

http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1451.pdf

like image 30
Wizard Avatar answered Sep 21 '22 19:09

Wizard