使用块?

Working with blocks?

在我最近参加的一次采访中,有人要求我预测代码段的输出。即使我做对了,我也无法解释它是如何得到的。 这是代码段。

int num =2;
int (^ myblock)(void)=^{
    return num*5;
};

NSLog(@"my block  call 1  %d",myblock());
num = 5;
NSLog(@"my block  call 2  %d",myblock());

谁能解释为什么两次的答案都是 10。? 谢谢

块外的变量不能改变,除非在它前面加上'__block'。所以 num 总是等于 2.

 __block int num =2;

那么你会得到10和25

在声明之前添加 __block 关键字,以便您可以访问块内的变量。

 __block int num =2;
    int (^ myblock)(void)=^{
        return num*5;
    };

    NSLog(@"my block  call 1  %d",myblock());
    num = 5;
    NSLog(@"my block  call 2  %d",myblock());

试试这个...

如果没有用 __block 标记,num 变量将在块内复制。这意味着外部作用域 num 和内部作用域 num 实际上保存在内存中的不同地址,更改一个不会影响另一个。要强制编译器使用相同的地址,请将变量标记为 __block

正如 Ryan Hodson 在他的 tutorial on Objective-C Blocks:

中所说的那样

Non-local variables are copied and stored with the block as const variables, which means they are read-only. Trying to assign a new value to the make variable from inside the block will throw a compiler error.

num定义为非局部变量。

The fact that non-local variables are copied as constants means that a block doesn’t just have access to non-local variables—it creates a snapshot of them. Non-local variables are frozen at whatever value they contain when the block is defined, and the block always uses that value, even if the non-local variable changes later on in the program.

如果要在块中反映 num 的新值,请将 num 声明为块变量

__block int num =2;  // *** Declared as block variable, value change will effect inside block  ***

让我们仅通过示例来理解它。

非局部(非块)变量*

int num =2;
int (^ myblock)(void)=^{
    return num*5;
};

NSLog(@"my block  call 1  %d",myblock());
num = 5;
NSLog(@"my block  call 2  %d",myblock());

结果:

我的块调用 1 10

我的块调用 2 10

块变量*

__block int num =2;
int (^ myblock)(void)=^{
    return num*5;
};

NSLog(@"my block  call 1  %d",myblock());
num = 5;
NSLog(@"my block  call 2  %d",myblock());

结果:

我的块调用 1 10

我的块调用 2 25