jbat100
jbat100

Reputation: 16827

Difference between blocks in C and Objective C

Here is an excerpt from the Blocks Programming Guide Conceptual Overview section

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.

I've been trying to make sense out of that last sentence but have failed to. The first and second part of the sentence seem incompatible to me (I'm probably missing something). Does this mean that blocks are not the same thing in C/C++ and objective C? Is this due to the way block objects in objective C are captured?

Upvotes: 7

Views: 806

Answers (2)

jbat100
jbat100

Reputation: 16827

Ok, after some looking around I have found some kind of pointers to answers (no pun intended). The clang block language specification states this about Objective-C Extensions

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.

Although I'm still confused as to whether the blocks runtime treats Objective C and C in the same way (creating Objective C objects even if pure C is being compiled) and if apple's proposed extension to C aims to allow using blocks in C/C++ without the creation of Objective C objects. Comments welcome.

Upvotes: 4

Joshua Weinberg
Joshua Weinberg

Reputation: 28688

The way blocks are defined, they require a bit of runtime support. Even though you can declare them in a plain C++ or C program and use Block_copy and Block_release to interact with them, the compiler is calling out to a linked in Blocks runtime in order to manage them for you.

Upvotes: 0

Related Questions