Sunday, November 29, 2009

Mix C++ code with Objective C for iPhone

Objective C is not the only language you can use to program for iPhone; you can use C/C++ and mix the C/C++ code with your Objective C code. And I recommend to do so:

Reason 1: for cross-platform purposes. If you use only Objective C then you are locked on the Apple platform. Don't give up the chance of porting your program to other devices such as Zune HD.

Reason 2: for the better C++ standard STL library. IMHO the STL library is much better than Objective C Cocoa libraries; it is portable and easier to use. Especially the container part.

To those who are worried, iphone run-time have full support for C++, including virtual function, exception handling and RTTI. And Xcode does support template.

There is no explicit boundary between C++ and Objective C when you code for iphone. You can write Objective C code in C++ classes/functions, and vice versa. But notice that the source code file other than headers should be named as ".mm".

Althrough you can mix C++ and Objective C, a good idea is to separate them for better portability and maintainability. When comes to a problem that both C++ and Objective C have solutions, I prefer to write the C++ code when possible and only write Objective C code where Cocoa library provides an easier solution, or when only it has the solution. For example, the Cocoa container classes suck but they do provide very easy to use persistance functions; so I use STL container and only translate the content to the Cocoa counter part when I need to save the content to a file.

A trick is that, you can provide Objective C implementation for C++ classes. I would use multiple implementation files for a C++ class interface: keep C++ only impl in one and Objective C impl in another.