I was recently asked by a fellow developer to relate my experience of writing multi-platform graphical applications with ObjectiveC++. This has become a very important topic, now that Apple has made it clear that they were not going to improve the Carbon framework and that everyone should use Cocoa/OjectiveC.
Writing ObjectiveC++ applications is straightforward, but there is no up to date documentation on the process. Generally, programmers want to use Cocoa/ObjectiveC for the UI and C++ for all “core” components. With C++, you get STL and a very large collection of well-tested code. In the end, although the object models in C++ and ObjectiveC are quite different, they can easily co-exist as they are both based on C and use common design patterns.
Main Objective C++ Documentation
This 2001 Apple release note is in serious need of an update, but it provides all the basic rules of mixing the two language.
Example XCode Project
The great time saver consist on finding a good example project. The Big Nerd Ranch provide this simple example where a C++ object is used to encapsulate the drawing code from within a Cocoa project.
Gotcha #1 – Embedding Method
The most basic decision that has to be made is how to actually represent the embedded C++ class: as a member object or as a pointer?
· CDrawing m_Drawing; // object or…
· CDrawing m_pDrawing; // pointer to object
Obviously, being able to embed an object directly would be awesome if the constructor and destructor were called automatically by the parent ObjectiveC view class.
This article as well as this one claim that this is possible using the latest GCC compiler. I’ve tried and it only works if the embedded class is very simple: no inheritance, and no member objects. This is useless for most applications, so basically, using a pointer is still best.
Gotcha #2 – Conditional C++ Includes
Every header file associated with an .MM file must start with something similar to this:
// ifdefs hide the C++ type from pure ObjC classes that import this file
Without this, the C++ in a header file will “contaminate” everything that #imports that header and result in a bunch of Xcode errors.
So there you have it. This is what I wish Apple would have put in a simple release note (together with *updated* example Xcode projects). Hope it helps. Let me know if you have further questions.