我知道如果复制了访问它的块,
也就是说,四个输出结果为:堆 => 堆 => 堆 => 堆,这不是我期望的结果:栈 => 栈 => 栈 => 堆。
能有人帮我澄清一下吗?
__block
变量将从栈移动到堆。但下面的测试代码告诉我,在复制块之前__block
变量已经被移动到堆中。也就是说,四个输出结果为:堆 => 堆 => 堆 => 堆,这不是我期望的结果:栈 => 栈 => 栈 => 堆。
能有人帮我澄清一下吗?
__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
__block int x; int *ptr = &x;
会发生什么? - Bryan Chen__NSStackBlock__
,__NSMallocBlock__
)。 - CodaFi