【发布时间】:2013-02-11 11:59:19
【问题描述】:
我知道如果访问它的 Block 被复制,__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
【问题讨论】:
-
你为什么要关心这个?如果变量从堆栈移动到堆,
__block int x; int *ptr = &x;会发生什么? -
这是一个实现细节。你应该尽量不要想太多。
-
记录块的类(是的,块是对象)也有助于确定它被复制到哪里(
__NSStackBlock__,__NSMallocBlock__)。 -
这是一个有趣的问题,我认为它不应该被关闭。
标签: ios objective-c objective-c-blocks heap-memory