What does the quot;__blockquot; keyword mean?(“__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...
- 它究竟告诉编译器什么?
- 它还有其他作用吗?
- 如果仅此而已,那么为什么首先需要它?
- 它在任何地方的文档中吗?(我找不到).
推荐答案
它告诉编译器任何被它标记的变量在块内使用时都必须以特殊方式处理.通常,块中也使用的变量及其内容会被复制,因此对这些变量所做的任何修改都不会显示在块之外.当它们被标记为 __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'
}
在此示例中,localCounter
和 localCharacter
在调用块之前都已修改.然而,在块内部,只有对 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"是什么意思?关键字是什么意思?
基础教程推荐
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01