块如何捕获其封闭范围之外的变量? [英] How does a Block capture the variables outside of its enclosing scope?

查看:118
本文介绍了块如何捕获其封闭范围之外的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道,Objective-C块可以捕获和设置其封闭范围之外的变量值.它是怎么做到的?

I know that an Objective-C Block can capture and set the value of variables outside of its enclosing scope. How does it do that?

推荐答案

它实际上相当简单,在Clang的《块实现规范》的部分.

It's actually fairly straightforward and described in Clang's Block Implementation Spec, in the "Imported Variables" section.

当编译器遇到如下所示的块时:

When the compiler encounters a Block like:

^{ if( numBalloons > numClowns) abort(); }

它创建了一个字面结构,其中包括-在这里很重要的两个元素.块中有一个指向可执行代码的函数指针,并且在块中引用的每个变量都有一个const字段.像这样:

it creates a literal structure that includes -- among other things -- two elements that are important here. There's a function pointer to the executable code in the Block, and a const field for each variable that's referred to inside the Block. Something like this:

struct __block_literal_1 {
    /* other fields */
    void (*invoke)(struct __block_literal_1 *);
    /* ... */
    const int numBalloons;
    const int numClowns;
};

请注意,invoke函数将使用指向此处定义的结构的指针;也就是说,该块在执行其代码时会自行通过.因此,代码可以访问结构的成员.

Notice that the invoke function will take a pointer to a struct of the kind that's being defined right here; that is, the Block passes itself in when executing its code. Thus, the code gets access to the members of the structure.

在声明之后,编译器将创建Block的定义,该定义仅使用引用的变量来初始化struct中的正确字段:

Right after the declaration, the compiler creates a definition of the Block, which simply uses the referenced variables to initialize the correct fields in the struct:

struct __block_literal_1 __block_literal_1 = {
    /* Other fields */
    __block_invoke_2,  /* This function was also created by the compiler. */
    /* ... */
    numBalloons,  /* These two are the exact same variables as */ 
    numClowns     /* those referred to in the Block literal that you wrote. *
 };

然后,在invoke函数内部,对所捕获变量的引用与结构的任何其他成员the_block->numBalloons一样进行.

Then, inside the invoke function, references to the captured variables are made like any other member of a struct, the_block->numBalloons.

对象类型变量的情况稍微复杂一些,但是应用相同的原理.

The situation for object-type variables is a little more complicated, but the same principle applies.

这篇关于块如何捕获其封闭范围之外的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆