Welcome to EMC Consulting Blogs Sign in | Join | Help

Filthy RIA

Using C++ with Objective-C (and iPhone SDK)

Here a small tip which makes sense but wasn't necessary obvious. You can have your C++ class both as .h file plus .cpp file but also as .h file plush .mm file. The important part is that the Objective-C class which includes it NEEDS to have the .mm extension, not the default .m. Otherwise you get C++ header syntax errors in the include line in the .m file.

So after having your Objective-C class renamed properly (with .mm extension) you can include your C++ class and using it with the usual C++ syntax.

Give the Foo class:

#ifndef FOO_H_INCLUDED
#define FOO_H_INCLUDED

class Foo
    {
    public:
        void setId(int newId);
        int getId();
    private:
        int myId;
    };

#endif // FOO_H_INCLUDED

You can use it like this:

Foo *foo = new Foo;
foo->setId(16);
NSLog(@"foo id: %i", foo->getId()); // foo id: 16
delete foo;

I am still thinking how much to use Objective-C and how much C++ in my future projects, especially for libraries, using C++ might mean more reusable, accessible, and probably readable, code but I found in the Objective-C dynamism a powerfull tool which can allow me to implement easily design patterns which I use regularly in the ActionScript world.

Published 03 September 2008 07:08 by christian.giordano
Filed under: , ,

Comments

No Comments
Anonymous comments are disabled

About christian.giordano

does stuff
Powered by Community Server (Personal Edition), by Telligent Systems