无夜之星辰
无夜之星辰

Reputation: 6158

Why did Apple design __block for write auto var in block?

We can read auto var in block:

int aVar = 1;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    NSLog(@"theVar==%d", aVar);
});

But can not write:

int aVar = 1;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    aVar = 2;
    NSLog(@"theVar==%d", aVar);
});

Xcode showed:Variable is not assignable (missing __block type specifier).

I know that when there is no __block,auto var pass to block as a copy so it's readonly.And with __block its address pass to block.

But I can't understand why Apple must design as this?Just copy address to block is not OK?Is there any potential problem If auto var in block without __block is writeable?

Upvotes: 0

Views: 63

Answers (1)

newacct
newacct

Reputation: 122439

It's not as simple as "with __block its address pass to block", because a block that captures the variable can outlive the scope that it's created in, and a local variable of automatic storage duration would become invalid at the end of the scope, so just capturing its address won't work.

A variable declared with __block actually involves a hidden structure behind the scenes, which can be "moved" from the stack to the heap if necessary so it can outlive the scope it was created in, and there are additional hidden fields that the compiler generates behind the scenes to allow someone accessing the variable to figure out the real location of the variable (stack or heap) at that time. Also, the blocks need to manage the memory of the copy of the variable on the heap. So defining a __block variable requires additional storage compared to the variable itself, and accessing a __block variable requires more levels of indirection and more memory management logic for the blocks involved. This additional complication should only be used if needed; therefore, variables captured by blocks are not __block by default.

Upvotes: 4

Related Questions