“__block"是什么意思?关键字是什么意思?

What does the quot;__blockquot; keyword mean?(“__block是什么意思?关键字是什么意思?)

本文介绍了“__block"是什么意思?关键字是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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. 它在任何地方的文档中吗?(我找不到).

推荐答案

它告诉编译器任何被它标记的变量在块内使用时都必须以特殊方式处理.通常,块中也使用的变量及其内容会被复制,因此对这些变量所做的任何修改都不会显示在块之外.当它们被标记为 __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.

有关示例和更多信息,请参阅 Apple 的 Blocks Programming Topics 中的 __block 存储类型.

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

重要的例子是这个:

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'
}

在此示例中,localCounterlocalCharacter 在调用块之前都已修改.然而,在块内部,只有对 localCharacter 的修改是可见的,这要归功于 __block 关键字.反之,块可以修改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.

这篇关于“__block"是什么意思?关键字是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:“__block"是什么意思?关键字是什么意思?

基础教程推荐