Please take a look at this piece of code:
NSMutableArray *array = [NSMutableArray array];
for (int i = 0; i < 10; i++)
{
void (^b)() = ^{printf("%d\n", i);};
[array addObject:b];
}
for (id obj in array)
{
void(^b)() = obj;
b();
}
[array removeAllObjects];
I expected this code to output 0, 1, 2 and so on but it prints 9 always. But why? Doesn't it capture i on every loop iteration? Why the last value is always captured? But what is more confusing for me is that if i change this line:
void (^b)() = ^{printf("%d\n", i);};
to
void (^b)() = [^{printf("%d\n", i);} copy];
then it starts printing 0, 1, 2 and so on. Can anybody please explain why it works this way?