【问题标题】:In Objective-C with ARC, what does compiler do when I define a block?在带有 ARC 的 Objective-C 中,当我定义一个块时编译器会做什么?
【发布时间】:2013-02-26 12:59:04
【问题描述】:

代码:

__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

为什么在圆弧和非圆弧中得到不同的输出?

【问题讨论】:

  • 唯一的区别是堆栈上的内存地址可能因运行而异
  • 这看起来与这个问题非常相似:stackoverflow.com/questions/15082265/….
  • @MartinR 是一样的。我得到了@Nikolai Ruhe 的答案。
  • @gelosie:您发布的输出看起来没有任何区别

标签: objective-c automatic-ref-counting block heap-memory stack-memory


【解决方案1】:

见 ARC 的documentation:

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

的效果

【讨论】:

    猜你喜欢
    • 2020-09-20
    • 2011-11-27
    • 1970-01-01
    • 1970-01-01
    • 2012-07-27
    • 2020-09-16
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    相关资源
    最近更新 更多