objective-c - C 和 Objective C 中的 block 之间的区别

标签 objective-c c objective-c-blocks

这是 Blocks Programming Guide Conceptual Overview 的摘录节

You can copy a block and even pass it to other threads for deferred execution (or, within its own thread, to a runloop). The compiler and runtime arrange that all variables referenced from the block are preserved for the life of all copies of the block. Although blocks are available to pure C and C++, a block is also always an Objective-C object.

我一直试图理解最后一句话,但没有成功。句子的第一部分和第二部分对我来说似乎不相容(我可能遗漏了什么)。这是否意味着 block 在 C/C++ 和 Objective-C 中不是一回事?这是由于捕获 Objective-C 中的 block 对象的方式造成的吗?

最佳答案

好的,环顾四周后,我发现了一些指向答案的指针(没有双关语意)。 clang block language specification关于 Objective-C 扩展的声明

Objective-C extends the definition of a Block reference type to be that also of id. A variable or expression of Block type may be messaged or used as a parameter wherever an id may be. The converse is also true. Block references may thus appear as properties and are subject to the assign, retain, and copy attribute logic that is reserved for objects.

All Blocks are constructed to be Objective-C objects regardless of whether the Objective-C runtime is operational in the program or not. Blocks using automatic (stack) memory are objects and may be messaged, although they may not be assigned into __weak locations if garbage collection is enabled.

虽然我仍然对 block 运行时是否以相同的方式对待 Objective C 和 C(创建 Objective C 对象,即使正在编译纯 C)以及是否 apple's proposed extension to C 感到困惑。旨在允许在不创建 Objective C 对象的情况下在 C/C++ 中使用 block 。欢迎评论。

关于objective-c - C 和 Objective C 中的 block 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8137608/

相关文章:

objective-c - 具有整数的数组的数组

c - 在 C 程序中嵌套 while 循环时遇到问题

c - 'SIGPIPE' : undeclared identifier in luasocket-2. 0.2

ios - 非平凡循环中的 block

iphone - 在 UImage 中显示渲染的图标

objective-c - 如何从 Objective-C 中的其他类访问 IBOutlets?

objective-c - 创建具有订单支持的 NSDictionary

ios - 将自定义对象添加到 block 内的 NSMutableArray 时遇到问题

定义为副本的 Objective-C block 属性不起作用

objective-c - 如何在swift中传递c函数指针