0

编码:

__block int x = 0;
int *pointerToX = &x;
NSLog(@"x's location is on the stack: %p", &x);    //stack
int (^block)() = ^{
    x += 1;
    return x;
};
NSLog(@"x's location is on the %@: %p", (&x == pointerToX ? @"stack" : @"heap"), &x);  
block();
NSLog(@"x's location is on the %@: %p", (&x == pointerToX ? @"stack" : @"heap"), &x);   
block = [block copy];    
NSLog(@"x's location is on the %@: %p", (&x == pointerToX ? @"stack" : @"heap"), &x);  

在非弧

x 的位置在堆栈上:0xbfffdba0

x 的位置在堆栈上:0xbfffdba0

x 的位置在堆栈上:0xbfffdba0

x 的位置在堆上:0x7195860

在弧中:

x 的位置在堆栈上:0xbfffdb70

x 的位置在堆栈上:0xbfffdb70

x 的位置在堆栈上:0xbfffdb70

x 的位置在堆上:0x7195860

为什么要在 arc 和 non-arc 中获得不同的输出?

4

1 回答 1

3

请参阅 ARC 的文档

[...] 当这些语义要求保留块指针类型的值时,它具有 Block_copy [...]

于 2013-02-26T13:04:17.100 回答