Blocks, loops and local variables
Consider the follow开发者_运维技巧ing code fragment:
for(/* some condition */) {
int x = rand();
[array addObject:^(){
NSLog(@"%d", x);
}]
}
for(void (^block)() in array) {
block();
}
Now I would expect this code snippet to print out all values assigned to x in that for loop; however it seems that all blocks share the same 'x' variable (presumably the last one).
Any idea why this is so and how I could fix the code to have each block contain the variable 'x' as it was at the time the block was defined?
The documentation specifically says not to do this. The reason is that blocks are allocated on the stack, which means they can go out of scope. For the same reason you can't access the variable x
outside of the first for
loop, you also shouldn't use that block. x
has gone out of scope, along with the block itself, and could contain any value.
To get around this, you can take a copy of the block like so:
for(/* some condition */) {
int x = rand();
void(^logBlock)() = ^() { NSLog(@"%d", x); }
[array addObject:[[logBlock copy] autorelease]];
}
This moves the block onto the heap, and should fix your problem.
精彩评论