什么是“__阻止”关键字是什 [英] What does the "__block" keyword mean?

查看:149
本文介绍了什么是“__阻止”关键字是什的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Objective-C中的 __ block 关键字究竟是什么意思?我知道它允许你修改块内的变量,但我想知道......

What exactly does the __block keyword in Objective-C mean? I know it allows you to modify variables within blocks, but I'd like to know...


  1. 它究竟是什么告诉编译器?

  2. 它还能做什么吗?

  3. 如果就是这样的话,为什么首先需要呢?

  4. 是否在文档中随处可见? (我找不到它。)

  1. What exactly does it tell the compiler?
  2. Does it do anything else?
  3. If that's all it does then why is it needed in the first place?
  4. Is it in the docs anywhere? (I can't find it).


推荐答案

它告诉编译器任何标记的变量当它在块内使用时必须以特殊方式处理。通常,复制也使用块中使用的变量及其内容,因此对这些变量所做的任何修改都不会显示在块之外。当它们用 __ block 标记时,在块内部进行的修改也可以在其外部显示。

It tells the compiler that any variable marked by it must be treated in a special way when it is used inside a block. Normally, variables and their contents that are also used in blocks are copied, thus any modification done to these variables don't show outside the block. When they are marked with __block, the modifications done inside the block are also visible outside of it.

示例和更多信息,请参阅块编程主题中的-SW6rel =noreferrer> __block存储类型

For an example and more info, see The __block Storage Type in Apple's Blocks Programming Topics.

重要的例子是这个一个:

The important example is this one:

extern NSInteger CounterGlobal;
static NSInteger CounterStatic;

{
    NSInteger localCounter = 42;
    __block char localCharacter;

    void (^aBlock)(void) = ^(void) {
        ++CounterGlobal;
        ++CounterStatic;
        CounterGlobal = localCounter; // localCounter fixed at block creation
        localCharacter = 'a'; // sets localCharacter in enclosing scope
    };

    ++localCounter; // unseen by the block
    localCharacter = 'b';

    aBlock(); // execute the block
    // localCharacter now 'a'
}

在此示例中,在调用块之前,将修改 localCounter localCharacter 。但是,在块内部,由于 __ block 关键字,只能修改 localCharacter 。相反,该块可以修改 localCharacter ,并且该修改在块外可见。

In this example, both localCounter and localCharacter are modified before the block is called. However, inside the block, only the modification to localCharacter would be visible, thanks to the __block keyword. Conversely, the block can modify localCharacter and this modification is visible outside of the block.

这篇关于什么是“__阻止”关键字是什的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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