Posts Tagged ‘Cross Platform’

Objective-C Blocks as Tuples Replacement

Thursday, August 14th, 2014

When programming you sometimes want to return multiple values from a function. The problem is that many languages only support one return value per function. A commonly used solution is to pass values by reference as input parameters to the function and “misuse” these as output parameters. Some languages (or libraries) – e. g. Swift – provide a tuple type where you can pack multiple values together so you can return multiple values as a tuple. You can also put your return values in some other kind of container, e. g. a dictionary or an array. All these solutions have their pitfalls, mostly some kind of loosing the type of the return values or having to box and unbox primitive values or just being cumbersome or hard to read.

Recently I came up with another idea how to get multiple return values from a function: If the used language supports some sort of closures (e. g. blocks in Obj-C) simply let the caller pass a closure that receives the return values with their proper types and call that closure to return the values.

An example in Objective-C:
Let’s create a class extension to NSArray that assumes the array just contains NSString objects and searches for the string that appears most often in that array. The result values are the number of occurrences of the string and the string itself.

@interface NSArray (MyExtension)
- (void)findMostUsedString:(void (^)(int count, NSString *string))result;

@implementation NSArray (MyExtension)

	// do the heavy calculation:
	int maxCount = 0;
	NSString *maxString = nil;
	@autoreleasepool {
		NSMutableDictionary *counters = [NSMutableDictionary dictionary];
		for(NSString *string in self) {
			@autoreleasepool {
				int count = [counters[string] intValue] + 1;
				counters[string] = @(count);
				if (count > maxCount) {
					maxCount = count;
					maxString = string;

	// return the result consisting of multiple values
	// by calling the passed block:
	result(maxCount, maxString);


Now you can use that function returning two values as simple as that:

NSArray *array = @[@"foo", @"bar", @"foo", @"foobar", @"42", @"foo"];
[array findMostUsedString:^(int count, NSString *string) {
	NSLog(@"Found \"%@\" %d times", string, count);

Output is:

Found "foo" 3 times

Cocoa and RAII

Wednesday, May 2nd, 2012

Today I want to write a bit about memory management and how I do it in my projects. Memory management is always an issue when writing programs, programmers have to know what they are doing, and there are some strategies how to handle it. Because I am doing OS X and iOS development most of the time and at the same time have specialized myself in cross-platform model programming, this article will focus on solutions I use in my daily work in these areas. While everybody talks about Manual Reference Counting or Garbage Collection (GC) or Automatic Reference Counting (ARC) when doing Cocoa development, I rarely hear Resource Acquisition Is Initialization (RAII). So maybe this is something new for the one or the other, although the idea of RAII is not so new, as you will see.

Manual Memory Management

When managing memory manually, it’s entirely up to the programmer when and how much memory to allocate and when to free it. This style should not be used anymore. Never. There are a lot of alternatives to this approach. This was used when programming “the old way” in C or C++, when alternative techniques where not so widely known, but you usually don’t see this anymore in modern code.

Examples (don’t do this at home):

 MyStruct *info = (MyStruct *)malloc(sizeof(MyStruct));
 info->something = 42;
 MyClass *object = new MyClass();
 delete object;

You can easily forget to free the allocated memory block resulting in a memory leak. Things get very complicated soon when you pass around pointers to allocated blocks of memory this way. The problem is to figure out when (and how) to free the allocated memory. Because there are no memory management concepts used here, there is no general solution to this problem and the programmer makes errors for sure as the code grows.

Manual Reference Counting

When doing Cocoa development and programming in Objective-C, one of the first things you learn is how to create and manage objects. In your code you write classes and instantiate objects of classes. One of the most important concepts in Cocoa is that every class should inherit from the base class NSObject and this class contains a retain counter. Every time you create or otherwise want to “own” an object, you increase the retain counter and once you don’t need the object anymore, you decrement this counter in your code through some special methods provided by NSObject, like retain, release or autorelease. When the retain counter falls back to zero, the object is automatically deleted. You never inspect the retain counter and you never delete objects by yourself anymore. You just follow a few very simple rules, any everything will be alright. No memory leaks or dangling pointers. Reference Counting is a simple but effective concept about the ownership of objects.


MyClass *object1 = [[MyClass alloc] init];
[object1 doSomething];
MyClass *object2 = [object1 retain];
// object1 and object2 point to the same object
[object1 release];
// object2 still points to a valid object
[object2 doSomethingElse];
[object2 release];
// no more valid references to the object; it automatically gets deleted

Garbage Collection

Some programming languages provide automatic garbage collection with sophisticated algorithms, so you don’t have to care about your memory management. If you don’t reference to objects anymore, they get freed. Hopefully. At some time. This has pros and cons, but I personally never was a big fan of garbage collection. Apple introduced a garbage collection solution for OS X programming (starting with OS X 10.5), but it never got its way into iOS and it does not seem to be very encouraged anymore. Everybody is talking about ARC (automatic reference counting) nowadays.


MyClass *object = [[MyClass alloc] init];
[object doSomething];

Note that you never have to call any code to “release” or “free” your object. The garbage collector does this magic for you. This is very convenient for the programmer, but does not come without cost. The garbage collector needs processor power, your application usually consumes more memory, and you never know when exactly your objects get freed.

Automatic Reference Counting (ARC)

A relatively new technology introduced for the Objective-C language is ARC (Automatic Reference Counting). This technique is basically the same as reference counting, but the compiler inserts the necessary retain and release calls by itself. So the manual counting becomes automatic. Basically it feels a lot like writing garbage collected code, but there is no garbage collector at runtime. You still have to know a bit about memory management, e. g. you have to avoid retain cycles by wisely declaring your references “strong” or “weak”  (something you don’t have to worry about in garbage collected code), but the reference counting itself is completely controlled by the compiler. Programmers don’t have the ability anymore to increment or decrement the retain counter explicitly. ARC has some advantages over garbage collection. Objects are always deleted immediately whenever they are no longer referenced and there is no additional processing power needed. When using garbage collecting, all your used code and libraries have to be prepared to run under garbage collecting, but not so for ARC: you can mix ARC and Non-ARC code at will. To use ARC you need the relatively new LLVM compiler. Currently there is a lot of buzz around ARC in the OS X and iOS developer scene.

Resource Acquisition Is Initialization (RAII)

Another way to control object lifetime is RAII. If you’re a Cocoa developer you may not have heard about this, but this technique is fairly old now – every C++ compiler provides this feature. The basic idea is to make use of the fact that data types (classes or structs) can have a destructor in C++. Variables have a precisely defined lifetime known by the compiler and the destructor is guaranteed to be called when the variable goes out of scope – even when exceptions are thrown. This is an advantage over the other mentioned “manual” techniques where you explicitly have to retain and release ownership on an object. If there is an exception thrown between these two steps, you usually have a memory leak. Not so when following the RAII idiom. You can see a simple example here:

class RAIIData {
    RAIIData(size_t count)
        : _data(malloc(count))
        , _size(count)

    ~RAIIData() {

    void *data() {
        return _data;

    size_t size() {
        return _size;

    void *_data;
    size_t _size;

Now you can use objects of this RAIIData type very easily:

RAIIData block(100);

This will allocate a block of memory of 100 bytes. This block is automatically freed when the code exits the scope of the block variable. This is also true for exceptions. RAII is one of the basic concepts used for implementing smart pointers (shared_ptr) provided by either the boost library or the new C++11 language standard. The basic idea of RAII is to combine two relating steps into one inseparable step: opening and closing a file, allocating and freeing memory, … or: retaining and releasing a reference counter!

Unfortunately there is no built-in support for the RAII idiom when using Cocoa. Objective-C objects are always created on the heap and referenced through a raw pointer; they can not be statically allocated and there is no concept of a smart pointer.

Still, I am using RAII a lot in my OS X and iOS code.

To describe that, I have to start a little earlier:

As said above, I specialized in writing cross-platform code. Although I love to code in Objective-C and write native UI code for OS X or iOS, I always searched for the best techniques to do cross-platform programming for the internal model of my apps. In my opinion, (Not Your Father’s) C++ is the way to go here. I used Java for some time, but although it’s a great language and it has its use cases or sure, it has not established well for end user software on desktop systems. Finally, on iOS Java is not available at all.

First of all, when holding references to objects of C++ classes, I always use smart pointers (boost::shared_ptr or std::shared_ptr). Everybody who used smart pointers knows what I am talking about. You never have to delete your objects yourself, they get automatically deleted whenever the lifetime of last referencing smart pointer ends. Using raw pointers to C++ objects is very discouraged.

While I think C++ (correctly used) is a very great language, in my opinion it lacks of good libraries. There is a lot of C++ code in the wild, but I never saw a good library (apart from boost) with great concepts that can be used as base for your apps. The language itself just provides some wicked containers and algorithms and things like that (that are great for specific needs), but that’s it. I think this is the biggest advantage of Cocoa: it provides an insanely great set of classes that are so simple but powerful. It makes fun to write code in Cocoa. It’s just like building worlds by using LEGO bricks. Expressed with some exaggeration, with plain C++ it’s like having a machine that can be used to build a machine that could eventually build LEGO bricks so you can finally start to build your world. But you’re far away from a usable set of reusable bricks. The very first thing I noticed in C++ is the lack of a good string class. I mean a real string class usable for human readable text. There is a string class in C++, but that’s a very dumb class. It’s for the “literal” meaning of “string”: a linear concatenation of objects (e.g. characters). But that’s it. The std::string class does not know what “text” is. There are no compare methods, there is no Unicode support, there’s nothing. It’s just a simple sequence of characters. Additionally, when using the std::wstring class you have the problem that wchar_t may have different size on different platforms and so on. So every time you start to code in C++ the very first thing you need is a usable string class, especially if you tend to write end user applications with UI. A user interface of an application uses text to communicate with the user in almost every case. I’ve not seen many end user applications that don’t use text of any sort. So, dealing with text is essential for a programmer! Unfortunately C++ does not help here much out of the box. As a resulting side effect, if you start to use third party C++ libraries, you’ll see very soon that many of these libraries provide their own string implementation. That’s not good. But that’s the way it currently is. In contrast, think about a Cocoa library from a third party: It’s totally natural (and convenient) to use NSString for text here – nobody would ever came to the idea to write his own string class to use in a Cocoa library.

So I love C++ as a language, but I also love the classes and concepts of Cocoa, and I want to write cross-platform code for the model. What’s the solution? I thought about solutions to use Objective-C and Cocoa libraries on other platforms, e.g. with GNUstep. But I finally decided against this in my projects. One problem is that you depend on having a compiler that can compile Objective-C code. Additonally GNUstep is fairly large and tries to port everything including the UI classes, but I am not interested in the UI classes of Cocoa. In my opinion on every platform you should use the native way to code the UI. I am interested in cross-platform model classes like strings and containers. My solution is using Core Foundation! Core Foundation is the “heart” of Cocoa and it is open sourced by Apple. It is written in C and many Cocoa classes are just Objective-C wrappers around Core Foundation. There is a great port named OpenCFLite that makes Core Foundation run on Windows. So, Core Foundation is great and (being part of Cocoa) well tested. But I don’t want to actually use it through an inconvenient C-API in my application code. So I wrote thin wrapper classes in C++ around Core Foundation and called it “maniCore”. And – to finally come back to the point – one of the basic idioms I used here is RAII. Here is some sample code how maniCore can be used:

namespace mani {
    String nullString;
    String emptyString("");
    String helloString("Hello");
    String sampleString = helloString.stringByAppending(" world!");
    CFRange worldRange1 = sampleString.rangeOf("world");
    // worldRange1.location is 6, worldRange1.length is 5
    // case insensitive search works, too:
    CFRange worldRange2 = sampleString.rangeOf("WoRlD", kCFCompareCaseInsensitive);
    // It also fully supports Unicode "for free"; provided by Core Foundation
    String everything("everything");
    String possible("possible");
    String(withFormat(), "%@ is %@, isn't that %s?", *everything, possible._NSString(), "great");
    MutableString mutableString;
    // easier appending through overwritten operator<<:
    mutableString << " is " << possible << "!";

You see mani::String objects can be created and used in various ways (only a very small set of possibilities is shown here) and you never have to care about retaining or releasing your objects, the same way as with smart pointers. It’s all done automatically using the RAII principle. Objects are freed automatically as soon as they are not used anymore. And you don’t need a garbage collector, and you don’t need a new compiler that does statical analysis and inserts code for you. It’s a simple old but robust technique provided by every C++ compiler based on the lifetime of variables.

Because maniCore objects wrap Core Foundation objects, they are retain counted internally. The classes just contain the CFTypeRef reference, and whenever you assign an object to another variable, the reference is copied and CFRetain() is called. Whenever the object is destructed, CFRelease() is called. So the internal Core Foundation object is deleted whenever the last referencing maniCore object is deleted. If you think about it, it has a minor disadvantage over Cocoa: In Cocoa you can pass plain pointers around – that’s very fast – and only if you need ownership of an object longer than for the current context, you send it a retain message. In maniCore you pass objects by value (not by pointer), and every time you pass such an object to another variable, CFRetain/CFRelease calls are made. This may be slower in some cases, but that’s more a theoretical problem. I’ve already used it a lot and never saw any performance problems. And if it ever gets a problem, you can simply move over to plain Core Foundation calls (or other solutions) for time critical tasks. Finally when adopting the new “move semantics” of the C++11 standard, this problem might occur even less often. Additionally when passing objects as parameters, you can pass them by const reference in many cases:

void myFunctionThatTakesAString(const mani::String& string);
To summarize: maniCore turns the Manual Reference Counting of Core Foundation into Automatic Reference Counting with the help of RAII (a feature provided by the C++ compiler):

Manual Reference Counting + RAII = Automatic Reference Counting

Of course I can convert easily between mani::String and NSString; this is needed to communicate between UI code and model code. And because I have the source of maniCore I can extend it at any time and adapt for my needs. Currently maniCore is private, but maybe I will release it to the public at some time in the future. I find it very handy, especially for cross-platform projects.

Core Foundation containers (CFArray, CFDictionary, etc.) were also wrapped into C++ classes. Because of the stricter type system of C++ compared to Objective-C I had to think of some tricks sometimes. There are cases where I find it even safer and a bit “funnier” to read, e.g. here is an example how to get a CFString out of an CFArray using maniCore wrappers:

namespace mani {
    Array array;
    // assume array is filled with Strings somehow,
    // now get the String at index 7:
    String string = array.get<String>(7);

When getting objects out of a Core Foundation or Cocoa Container, you always have to know what type they are. The container itself doesn’t do any type checking here. In Cocoa the getter usually just returns objects of type id and this is implicitly casted to the type of your variable by the compiler. When directly using the C-API of Core Foundation you usually have to cast the type yourself. I want to avoid casting in the higher level code that uses maniCore and because of the stricter type system of C++ I had to specify the type in the getter of my C++ wrapper. I did that with some template magic and I ended up with the nice verbose get<Type> solution, that even can do type checking, if desired (e.g. in the Debug build).

In maniCore I wrote another crazy class: a container for Cocoa pointers (NSObject and all subclasses) that provides the RAII idiom for them, too. You can use it as follows:

namespace mani {
    Cocoa<NSString> string = @"Test";
    NSUInteger stringLength = [*string length];

The overwritten operator* returns the internal Cocoa pointer for easy usage.

As soon as the string variable goes out of scope, the internal NSString object is sent a release message. It’s like a smart pointer, but for Objective-C objects instead of C++ objects and directly using the internal retain counter of these Cocoa objects instead of implementing an own solution. This is very convenient when being used as instance variables. You do not have to release these instance variables in your dealloc method anymore. They are automatically destructed. You just have to make sure to have turned on GCC_OBJC_CALL_CXX_CDTORS (Call C++ Default Ctors/Dtors in Objective-C) in your compiler settings:

@interface MyClass {
    mani::Cocoa<NSString> _internalString;

It can also be used for variables with getters and setters, especially for IBOutlets. Although in this case you’re not able to @synthesize the getter and setter, but it’s very easy to write it yourself, because the entire retain/release procedure of the setter is hidden (and written only once) in the mani::Cocoa implementation:

@interface MyClass {
    mani::Cocoa<NSButton> _button;
@property (nonatomic, retain) IBOutlet NSButton *button;
@implementation MyClass
- (NSButton *)button
    return *_button;
- (void)setButton:(NSButton *)button
    _button = button;


Note that you don’t have to think about overwriting dealloc and free the instance variable. It’s done automatically.

Another nice example it how you can use a local NSAutoreleasePool by using the RAII-Wrapper:

    mani::Cocoa<NSAutoreleasePool> pool(mani::alreadyRetained(), [[NSAutoreleasePool alloc] init]);
    // do your work ...
    // if pool gets out of scope, it's automatically released

You can even wrap this verbose bit of code into another self-made special “AutoAutoreleasePool” class that hides the call above and you can even make it cross-platform by simply doing nothing in the Windows specific implementation, so you end up with that in your code:

    AutoAutoreleasePool pool;
    // do your work ...
    // if pool gets out of scope, it's automatically released

You see there are a lot of things possible when mixing C++ and Objective-C. Although C++ is a very old language, I am still a huge fan of it and wanted to demonstrate that a modern usage of C++ is not the way as most people have seen in their life. There is a lot of cryptic and ugly C++ code out there. Don’t use it this way. C++ has a lot of possibilites, that makes it difficult and requires a lot of knowledge and discipline to use it “the right way”, but I don’t like it when people argue “Objective-C is better” or “C++ is a hell of a language” etc. When used in a modern and smart way it has cool features. I demonstrated how I use it to write cross-platform code in a style that’s pretty comparable to Cocoa using ARC.

I love to write Objective-C code but I also love to write good C++ code and became kind of an expert in combining both together.

CoreFoundation plus QuickTime on Windows

Monday, April 26th, 2010









Building Boost on Snow Leopard

Wednesday, October 14th, 2009

Behind the scenes we’re working on great stuff that requires the phantastic Boost libraries. Unfortunately building those libraries isn’t always that easy. Starting with Snow Leopard and its Xcode 3.2 we were no longer able to build universal binaries of Boost the way we used to. After reading a lot of articles and forums for a solution (none of them worked for us) we came up with our own solution.

The goal: we want to have 4-way universal binaries of static Boost libraries. That is PowerPC 32-Bit, PowerPC 64-Bit, Intel 32-Bit, and Intel 64-Bit.

The problem: As soon as we tried to use address-model=32_64 in the bjam command we just got weird errors.

The solution: It’s pretty easy; just avoid compiling for multiple architectures at once. We solved the problem by compiling for each architecture separately and finally putting things together into universal binaries using the lipo tool.

I wrote a perl script to accomplish that. Please be aware that I’m not a very experienced scripter. My primary programming languages are Obj-C, C++, and Java, but I avoid scripting whenever possible. So the following script may be by far not the best solution and I “hacked” it together for our own purposes only. The script is currently working for Boost 1.40 and the resulting binaries are installed into /build_external.

The way we build the Boost libraries they should be usable on any PPC- or Intel-Mac running Mac OS X 10.4 (Tiger) or later in 32-Bit and 64-Bit applications.

Feel free to use the script and adapt it for your specific needs. Use at your own risk.

# usage:
# - make sure $PREFIX and $VER are correct
# - Extract the boost source archive and cd into the extracted folder (e.g. "boost_1_40_0").
# - execute this script

use strict;
use File::Basename;

my $PREFIX = "/build_external";
my $VER = "1_40";
my $GCC = "xgcc40-mt";

# compile boost for PPC 32-Bit:

system("bjam --prefix=$PREFIX --libdir=$PREFIX/libPPC32 --layout=versioned toolset=darwin-4.0 macosx-version=10.5 macosx-version-min=10.4 architecture=power address-model=32 link=static install");

#compile boost for PPC 64-Bit:

system("bjam --prefix=$PREFIX --libdir=$PREFIX/libPPC64 --layout=versioned toolset=darwin-4.0 macosx-version=10.5 macosx-version-min=10.4 architecture=power address-model=64 link=static install");

#compile boost for Intel 32-Bit:

system("bjam --prefix=$PREFIX --libdir=$PREFIX/libIntel32 --layout=versioned toolset=darwin-4.0 macosx-version=10.5 macosx-version-min=10.4 architecture=x86 address-model=32 link=static install");

#compile boost for Intel 64-Bit:

system("bjam --prefix=$PREFIX --libdir=$PREFIX/libIntel64 --layout=versioned toolset=darwin-4.0 macosx-version=10.5 macosx-version-min=10.4 architecture=x86 address-model=64 link=static install");

#collect all boost libraries in libPPC32, libPPC64, libIntel32, and libIntel64:

my %libs;
my @globLibs;
my $lib;

@globLibs = glob("$PREFIX/libPPC32/libboost_*-$GCC-$VER.a");
foreach $lib (@globLibs) {
%libs = map { $_ => 1 } keys %libs, basename($lib);
@globLibs = glob("$PREFIX/libPPC64/libboost_*-$GCC-$VER.a");
foreach $lib (@globLibs) {
@globLibs = glob("$PREFIX/libIntel32/libboost_*-$GCC-$VER.a");
foreach $lib (@globLibs) {
@globLibs = glob("$PREFIX/libIntel64/libboost_*-$GCC-$VER.a");
foreach $lib (@globLibs) {

#iterate over all boost libraries and execute the appropriate lipo command to create universal libraries in lib:

my $cmd;
my $archs;
my $archLib;
foreach $lib (keys %libs) {
$archs = "";
$cmd = "lipo -create";
$archLib = "$PREFIX/libPPC32/$lib";
if (-e $archLib) {
$cmd = $cmd." ".$archLib;
$archs = $archs." ppc";
$archLib = "$PREFIX/libPPC64/$lib";
if (-e $archLib) {
$cmd = $cmd." ".$archLib;
$archs = $archs." ppc64";
$archLib = "$PREFIX/libIntel32/$lib";
if (-e $archLib) {
$cmd = $cmd." ".$archLib;
$archs = $archs." i386";
$archLib = "$PREFIX/libIntel64/$lib";
if (-e $archLib) {
$cmd = $cmd." ".$archLib;
$archs = $archs." x86_64";

$cmd = $cmd." -output $PREFIX/lib/$lib";

print("----------------------------------------------\nCreating universal$archs library $lib ...\n");
# system("lipo -info $PREFIX/lib/$lib");

Building Boost for the iPhone

Wednesday, May 6th, 2009

We’re working on very interesting stuff for new products behind the scenes. It’s a special challenge to write cross platform code. For that reason we are creating a very solid code base that we can reuse in all future products. We decided to use C++ and wanted to support Mac OS X, Windows, iPhone OS and potentually Linux. Maybe I’ll write more about our concepts and decisions about that in a future post, but for now I’ll concentrate on Boost.

Boost is a collection of free cross platform and high-quality C++ libraries. Most of the classes can be used “header only”, so you include the appropriate header file in your code and it “just works”. Maybe the most famous class of Boost is the Smart Pointer class shared_ptr. In our case we also needed the compiled libraries of Boost. Therefore we had to compile it amongst others for the iPhone. There are a few difficulties when building it for the iPhone and I had to google a lot until I found out all the details. Now I want to share my solution how I managed to build the Boost libraries for the iPhone – and here it is. I tried it with Boost version 1.42.0:

  1. You need a Mac with Mac OS X and installed iPhone SDK, of course.
  2. Download the Boost sources and extract them somewhere on your hard disc.
  3. In the directory with the Boost sources, open the file tools/build/v2/user-config.jam and fill it with the following content:

    using darwin : 4.2.1~iphone
       : <striper>
       : <architecture>arm <target-os>iphone <macosx-version>iphone-3.0

    using darwin : 4.2.1~iphonesim
       : <striper>
       : <architecture>x86 <target-os>iphone <macosx-version>iphonesim-3.0

    You have to adjust the paths if you have installed the iPhone SDK at a different location.

  4. Now open the file tools/build/v2/tools/darwin.jam and add the missing line

    iphone-3.1.3 iphonesim-3.1.3

  5. To build the Boost libraries for the iPhone Device, do the following:

    bjam --prefix=/path/for/BoostiPhoneDeviceLibs --layout=versioned toolset=darwin architecture=arm target-os=iphone macosx-version=iphone-3.0 define=_LITTLE_ENDIAN link=static install

    Replace /path/for/BoostiPhoneDeviceLibs with the path were you want to have the final Boost libraries and headers located.

  6. To build the Boost libraries for the Simulator, do the following:

    bjam --prefix=/path/for/BoostiPhoneSimulatorLibs --layout=versioned toolset=darwin architecture=x86 target-os=iphone macosx-version=iphonesim-3.0 link=static install

    Replace /path/for/BoostiPhoneSimulatorLibs with the path were you want to have the final Boost libraries and headers located.

Unfortunately there are a few errors and warnings when building Boost for the iPhone this way. But because we currently do not use the affected classes yet, we did not spend much time into that.