我知道__block
如果一个访问它的块被复制,一个变量将从堆栈移动到堆中。但是下面的测试代码告诉我变量在块复制之前__block
被移动到堆中。
也就是说,四个输出是:stack => heap => heap => heap,这不是我预期的结果:stack => stack => stack => heap。
有人可以纠正我吗?
__block int x = 0;
int *pointerToX = &x;
//1. It's on the stack
NSLog(@"x's location is on the stack: %p", &x);
int (^block)() = ^{
x += 1;
return x;
};
//2. I think its stack, but it's heap
NSLog(@"x's location is on the %@: %p", (&x == pointerToX ? @"stack" : @"heap"), &x); //it's heap not stack
block();
//3. I think its stack, but it's heap
NSLog(@"x's location is on the %@: %p", (&x == pointerToX ? @"stack" : @"heap"), &x); //it's heap not stack
block = [block copy]; // The variable x will be moved to the heap
//4. I think its stack, but it's heap
NSLog(@"x's location is on the %@: %p", (&x == pointerToX ? @"stack" : @"heap"), &x); //heap