The documentation specifically states that this should not be done . The reason is that blocks are allocated on the stack, which means that they can go out of scope. For the same reason, you cannot access the variable x
outside the first for
loop, you should not use this block either. x
went out of scope with the block itself and can contain any value.
To get around this, you can take a copy of the block as follows:
for() { int x = rand(); void(^logBlock)() = ^() { NSLog(@"%d", x); } [array addObject:[[logBlock copy] autorelease]]; }
This moves the block to the heap and fixes your problem.
source share