Wed, 10 Mar 2010 06:31:53 GMT

Retaining C++ Objects

C++ and Objective-C do not always mix too well, although the two languages are fully compatible.

With respect to compilation phases, alternating between C, C++, Objective-C and Objective-C++ presents no problem. You just write your software accordingly, freely mixing C, Objective-C, C++ and Objective-C++. Just make sure that the compiler knows what each translation unit contains, normally by source file extension: c for C; cc or cpp or cxx for C++; m for Objective-C; and mm for Objective-C++.

That being specified correctly, your sources compile and link without issues. Only when you start running the code side-by-side however, you might find that memory management can become something of a mishmash. Basic C++ fundamentally has no memory management; I mean nothing automatic. Asking for memory when you want it, freeing memory when you’re done with it: that is all bare C++ gives you. So you typically just roll your own, or find some more-advanced alternative such as Boehm’s garbage collector.

Wouldn’t it be nice however, if you could just simply retain, release and auto-release your C++ objects, just like you do with NSObjects? It would be very nice.

This article outlines a little “trick” for retaining C++ objects on Mac and iPhone. It takes advantage of C++ inheritance; and is simple, so no dependence on internals of CFTypeRef or NSObject. The memory cost is low; just one additional NSObject-derived object per retained C++ object. Final feature, implementation separates from interface by design. Hence you can include retaining within bodies of source without the things being retained having any knowledge of Objective-C. Translation units remain plain old C++, no additional dependencies. The implementation exists apart.

MIT-licensed code provided in full.


Fri, 22 Aug 2008 09:22:00 GMT

Permutation class

Permutations! I’ve hit this issue quite a number of times in my life: at university, at work. It’s not unusual to encounter problems where it’s very handy to able to iterate all possible permutations of something. And catch is: standard libraries sometimes do not offer any help. The engineer is left to tackle the problem by him- or herself.


Thu, 21 Aug 2008 11:04:00 GMT

Factorial function in Objective-C

Factorial, denoted by n! and defined as the product of all positive integers less than or equal to n.


Wed, 20 Aug 2008 08:03:00 GMT

Sorting an array by another array

Suppose you want to sort an array of strings according to some prescribed order. In other words, you are given an array of strings as input, plus another array of strings describing the required ordering. The result is another array of strings equal to the first but sorted by the second.