我很难理解苹果块编程的这一部分

时间:2012-10-25 08:37:43

标签: ios

来自apple block programming,任何人都可以告诉我这是什么意思

  

封闭词法范围本地的堆栈(非静态)变量是   捕获为const变量。

2 个答案:

答案 0 :(得分:3)

说你有:

int i = 5; // in stack

然后在块中你有:

...
i++; // can't do that, because i now inside the block is a const
...

您要将__block添加到i声明,以便能够在块内更改i的值,如下所示:

__block int i = 5; // remove __block and see the error

void (^myBlock)(void) = ^{
    NSLog(@"[inside block] i = %i", i); // no error even without __block
    i++; // error here without __block
};

myBlock();

NSLog(@"[outside block] i = %i", i);

答案 1 :(得分:1)

这意味着如果在定义块的范围内声明了局部变量,则可以在块中引用该变量,但不能更改其值,也不能看到从外部对其值进行的任何更改。

//-- this is the "Stack (non-static) variables local to the enclosing lexical scope"
int x = 123;

void (^printXAndY)(int) = ^(int y) {

   printf("%d %d\n", x, y);             //-- you can use x inside the block
};

x表现为一个const变量,即,在定义块时它的值被冻结,你无法修改它。

将此与__block限定符的使用进行对比,以便能够修改该变量的值。

相关问题