Just because it bit me again for a millionth time:
int a = 0;
void(^block)(void) = ^{ printf("%d", a); };
a = 1;
block();
outputs 0, because the value of a is copied to the block when it is declared.
If you want it to track the variable instead, you have to do:
__block int a = 0;
void(^block)(void) = ^{ printf("%d", a); };
a = 1;
block();
This outputs 1, as you would expect, since the block only gets a reference to a. It might look obvious this way, but consider this code:
void(^calc)(int,int) = ^(int a, int b) {
printf("%d ", a);
if(b<10000) calc(b, a+b);
};
calc(0, 1);
(Bonus points if you know what sequence this should output!) Since the variable block isn’t defined when the block is declared, it points to a bogus value and crashes. You have to do it this way:
__block void(^calc)(int,int) = ^(int a, int b) {
printf("%d ", a);
if(b<10000) calc(b, a+b);
};
calc(0, 1);
« About Apple’s Bug Reporter Mac OS X Range Selection Behavior »
