2013-02-26 18 views
0

代碼:在使用ARC的Objective-C中,編譯器在定義塊時做了什麼?

__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的位置是在堆棧上:​​3210

X的位置是在堆棧上:​​3210

X的位置是在堆棧上:​​3210

X的位置在堆上:0x7195860

爲什麼得到差異輸出弧和非弧?

+1

唯一的區別是堆棧上的內存地址可能因運行而異 – 2013-02-26 13:04:09

+0

這看起來與此問題非常相似:http://stackoverflow.com/questions/15082265/why-is-a-block-variable-is-移動至所述堆先於所述嵌段是複製的。 – 2013-02-26 13:36:52

+0

@MartinR它是一樣的。我通過@ Nikolai Ruhe得到了答案。 – gelosie 2013-02-26 14:06:02

回答

3

見ARC的documentation

[...]每當這些語義呼籲保留塊指針類型的值,它有一個Block_copy的效果[...]

相關問題