Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C Blocks in C

While reading through the blocks conceptual overview in Apple Docs, I saw the following statement:

Although blocks are available to pure C and C++, a block is also always an Objective-C object.

How is this possible? I mean an Objective-C object available in pure C. I'm getting confused.

like image 993
Rakesh Avatar asked Mar 20 '14 16:03

Rakesh


People also ask

What is meant by Objective-C?

Objective-C is the primary programming language you use when writing software for OS X and iOS. It's a superset of the C programming language and provides object-oriented capabilities and a dynamic runtime.

Is Objective-C for Apple?

Objective-C was the standard programming language supported by Apple for developing macOS (which descended from NeXTSTEP) and iOS applications using their respective application programming interfaces (APIs), Cocoa and Cocoa Touch, until the introduction of Swift in 2014.


2 Answers

How is this possible? I mean an Objective-C object available in pure C.

Matt Gallagher wrote an article that nicely explains how blocks work. In a nutshell, blocks are defined as structs that meet the requirements to be a valid Objective-C object (for example, the struct starts with an isa pointer). None of this causes a problem for C, and the compiler knows what the definition of a block is, so even when compiling plain old C it can still do the right thing to make blocks work.

The added Objective-C aspect of blocks doesn't affect how blocks are used in C, but still provides the ability to treat blocks as objects so that they can be added to collections and otherwise managed like any other object.

This isn't really so strange. If you think about it, all Objective-C objects are "available" in C at some level -- the entire Objective-C runtime consists of C functions that manipulate structures that represent Objective-C objects and classes. And even disregarding that, blocks aren't the first example of a data type that's usable in both C and Objective-C -- we've had toll free bridging between Foundation and Core Foundation for many years. The implementation of blocks may be somewhat different, but it's not a new thing to have objects that work in both worlds.

like image 152
Caleb Avatar answered Sep 19 '22 09:09

Caleb


Objective-C can be freely mixed with C. As long as your class has a C API (which blocks do, with Block_copy, Block_release, etc.), the C code doesn't care if it's implemented in Objective-C or C.

like image 25
Chuck Avatar answered Sep 20 '22 09:09

Chuck