Archive for the ‘Development’ Category

Swift Property Wrapper for Cancellable

Saturday, July 4th, 2020

With SwiftUI Apple developed a new and modern way to realize user interfaces for apps. It’s faszinating how the language Swift itself with new features and all the frameworks perfectly fit together to form the capabilities of SwiftUI as a whole. One important piece of that puzzle is the Combine framework that provides a kind of “reactive” API. If you write view model code for SwiftUI, you regulary have to deal with Cancellables and you end up with the following principle over and over again:

class Someclass : ObservableObject {

    private var someCancellable: AnyCancellable? {
        didSet {

    private var anotherCancellable: AnyCancellable? {
        didSet {

    deinit {

This is a perfect example to make use of a Property Wrapper! To be honest, I am wondering why Apple does not provide this out of the box. Property Wrappers are a way in Swift to define a customized behaviour for properties. Here’s my solution to improve and automate the repetitive code from above:

import Combine

class AutoCancel<Value> where Value: Cancellable {
    var wrappedValue: Value? {
        didSet {
            // cancel the old Cancellable whenever a new is set:

    deinit {
        // cancel the Cancellable on deinit

It’s short and easy, but has a huge impact: Now you can replace the initial verbose code from above with the following:

class Someclass : ObservableObject {
    @AutoCancel private var someCancellable: AnyCancellable?
    @AutoCancel private var anotherCancellable: AnyCancellable?

That’s it! The code size reduced dramatically and it is much easier to type and to read, and it is also less error-prone because you don’t have to think about cancelling these properties in the deinit block anymore.

Have fun and happy coding!

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)

- (void)findMostUsedString:(void (^)(int count, NSString *string))result
	// 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

Exploring iOS 7 Rounded Corners

Thursday, June 20th, 2013

Apple announced iOS 7 at the WWDC 2013. Compared to the previous iOS versions it gets a whole new look for the first time. There’s a lot of discussion going on whether it’s good or bad design. I personally like it very much, and it reminds me a bit of the huge step from Mac OS 9 to Mac OS X years ago. Many things have changed in iOS 7, but one little detail attracted my attention and that’s what this article is about: rounded corners. Apple is very obsessed about every little detail; in my opinion that’s one of the secrets why they make so beautiful and successful products. Usually a rounded corner is just a quarter of a circle, one might think. But Apple changed the form factor of rounded corners in iOS 7. Here is a little comparison:

Rounded Corners in iOS 6Rounded Corners in iOS 7

Animated iOS 6 vs 7 Comparison

To me, the corners in iOS 7 look much smoother and organic. These new corners are everywhere in iOS 7. One reason for this is that as a developer you get these new corners for free. Whenever you use the existing functions of the operating system to create rounded corners, you get the improved ones in iOS 7, e. g. when calling [UIBezierPath bezierPathWithRoundedRect:cornerRadius:].

Here is an image that shows the difference between the old and the new corners:

Corner Difference between iOS 6 and iOS 7

You see that not many pixels have changed, even at this big size, but nevertheless it has some subtle but perceptible impact in how the corners look and feel.

Currently there are a few discussions on how Apple draws these new corners; even some mathematical equations are published. I took a rather pragmatic approach to analyze it: I created a small test app that lets the system create a rounded rectangle and then introspects and visualizes the elements of the returned bezier path. Then I launched this app on iOS 6 and iOS 7. Here are the results:

Rounded Corner Bezier Path on iOS 6
Rounded Corner Bezier Path on iOS 7
A red cross marks every point where a straight line is drawn to. An orange cross with two green control points in between define a bezier curve. As you can see there are four little points where the path is not perfect yet: there are four (very) short straight lines from a curve end point (orange) to a new point (red) very closely together. These unnecessary four short lines can be stripped out of the path; maybe this will be fixed in the final version of iOS 7.

What’s also interesting is the fact that the edges of the rectangle are bent much earlier than before. In the picture below the blue area is where the lines are curved in iOS 6. The red area is where the lines are curved in iOS 7. It’s more than half the corner radius earlier:

Line bending areas

Update: Together with @flarup and @marcedwards we tried to figure out the exact radius for the corners being used for the app icons in iOS 7. Additionally I filtered out the annoying short lines metioned above and exported the UIBezierPath as SVG file. As far as we can see a radius of 27 pixels at 120×120 pixel icon size produces a pretty good match. Download it here.

In case you wonder how I introspected the UIBezierPath to draw the images above – here is the UIView code:

@interface CornerTestView ()
@property (nonatomic) CGPoint previousPoint;

@implementation CornerTestView

static void pathInspector(void *info, const CGPathElement *element)
	CornerTestView *view = (__bridge CornerTestView *)info;
	[view addElement:element];

- (void)drawRect:(CGRect)dirtyRect
	[[UIColor whiteColor] setFill];

	CGRect rect = self.bounds;
	CGFloat size = MIN(CGRectGetWidth(rect), CGRectGetHeight(rect)) - 20;
	size = round(size / 2) * 2;
	rect = CGRectMake(round(CGRectGetMidX(rect) - size / 2), round(CGRectGetMidY(rect) - size / 2), size, size);
	CGFloat radius = size / 4;
	UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:radius];
	[[UIColor colorWithRed:0.90 green:0.93 blue:1.0 alpha:1.0] setFill];
	[path fill];

	CGPathRef cgPath = path.CGPath;
	CGPathApply(cgPath, (__bridge void *)(self), pathInspector);

static UIBezierPath *crossAtPoint(CGPoint p)
	UIBezierPath *cross = [UIBezierPath bezierPath];
	cross.lineWidth = 0.5;
	[cross moveToPoint:CGPointMake(p.x - 2, p.y - 2)];
	[cross addLineToPoint:CGPointMake(p.x + 2, p.y + 2)];
	[cross moveToPoint:CGPointMake(p.x - 2, p.y + 2)];
	[cross addLineToPoint:CGPointMake(p.x + 2, p.y - 2)];
	return cross;

- (void)addElement:(const CGPathElement *)element
	switch (element->type) {
		case kCGPathElementMoveToPoint:
			[[UIColor grayColor] setStroke];
			[crossAtPoint(element->points[0]) stroke];
			self.previousPoint = element->points[0];
		case kCGPathElementAddLineToPoint:
			UIBezierPath *line = [UIBezierPath bezierPath];
			line.lineWidth = 0.25;
			[[UIColor lightGrayColor] setStroke];
			[line moveToPoint:self.previousPoint];
			[line addLineToPoint:element->points[0]];
			[line stroke];

			[[UIColor redColor] setStroke];
			[crossAtPoint(element->points[0]) stroke];
			self.previousPoint = element->points[0];
		case kCGPathElementAddQuadCurveToPoint:
			UIBezierPath *line = [UIBezierPath bezierPath];
			line.lineWidth = 0.25;
			[[UIColor lightGrayColor] setStroke];
			[line moveToPoint:self.previousPoint];
			[line addLineToPoint:element->points[0]];
			[line addLineToPoint:element->points[1]];
			[line stroke];
			[[UIColor cyanColor] setStroke];
			[crossAtPoint(element->points[0]) stroke];
			[[UIColor magentaColor] setStroke];
			[crossAtPoint(element->points[1]) stroke];
			self.previousPoint = element->points[1];
		case kCGPathElementAddCurveToPoint:
			UIBezierPath *line = [UIBezierPath bezierPath];
			line.lineWidth = 0.25;
			[[UIColor lightGrayColor] setStroke];
			[line moveToPoint:self.previousPoint];
			[line addLineToPoint:element->points[0]];
			[line addLineToPoint:element->points[1]];
			[line addLineToPoint:element->points[2]];
			[line stroke];
			[[UIColor greenColor] setStroke];
			[crossAtPoint(element->points[0]) stroke];
			[crossAtPoint(element->points[1]) stroke];
			[[UIColor orangeColor] setStroke];
			[crossAtPoint(element->points[2]) stroke];
			self.previousPoint = element->points[2];
		case kCGPathElementCloseSubpath:


Have fun!

Blocks not capturing “by reference” variables

Monday, May 21st, 2012

I recently stumbled over a strange case when using blocks.

Please look at the following bit of  Objective-C++ code:

typedef void (^BlockType)();

static BlockType blockTestByValue(const int value)
	return [[^{NSLog(@"blockTestByValue &value = %p", &value);} copy] autorelease];

static BlockType blockTestByReference(const int& value)
	return [[^{NSLog(@"blockTestByReference &value = %p", &value);} copy] autorelease];

void test()
	BlockType direct;
	BlockType byValue;
	BlockType byReference;
		int value = 42;
		NSLog(@"&value = %p", &value);
		direct = [[^{NSLog(@"direct &value = %p", &value);} copy] autorelease];
		byValue = blockTestByValue(value);
		byReference = blockTestByReference(value);

Calling test() gives the following output:

&value = 0x7fff5fbff44c
direct &value = 0x100c26a10
blockTestByValue &value = 0x100c26990
blockTestByReference &value = 0x7fff5fbff44c

You see, we have a stack based variable value here that is used by blocks that are executed outside the living context of the variable value. Therefore the value variable gets “captured” by the block and a copy is made. This is true for all cases – except for the case where I pass the value variable by reference to a function! I don’t see any reason why the variable should not be captured in this case. In my opinion the blockTestByReference case should behave exactly like the direct case, because in both cases value is referencing exacly the same variable.

Any comments? Did I miss something in the specification of blocks, or did a discover a bug in the compiler?


I found the behavior described in the language specification:

For example, given class Foo with member function fighter(void):
      Foo foo;
      Foo &fooRef = foo;
      Foo *fooPtr = &foo;

...a Block that used foo would import the variables as const variations:
       const Foo block_foo = foo;	// const copy constructor
       const Foo &block_fooRef = fooRef;
       Foo *const block_fooPtr = fooPtr;

So the compiler is really correct here. One must be very careful when using variables declared by reference in blocks!

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.

Grand TableView Dispatch

Friday, August 19th, 2011

Just a little programming trick that might be interesting for other programmers:

I am working on a project where I have a (view based) NSTableView that should display a value in each row. These values are calculated from other values that are fetched from a database. While the performance of getting one single value is acceptably fast (under 0.1 seconds) for other use cases of the application, this sums up in the table view and noticably blocks the user interface whenever the table needs to be reloaded or when scrolling through the table.

My first idea was to calculate the values in a separate thread and then update the GUI whenever a value is available. Problem here is that the model is not thread-safe at this point and that would be a ton of work to change.

So I decided that the values for the table should be calculated on the main thread as before, but the main runloop should get a chance to do its work between every calculation of a single value to keep the user interface as responsive as possible. A great situation for Grand Central Dispatch and the use of Blocks! So I wrote something like that for every requested value in the table view:

dispatch_async(dispatch_get_main_queue(), ^{
+++// calculate value and update the GUI

… unfortunately, that did not work as expected. The GUI still blocked until all values for all requested rows of the tableview where calculated. It seems the blocks were correctly added to the main queue, but as soon as the process returned to the runloop, the whole queue was processed in one pass without checking for events in between the individual enqueued blocks. So the behaviour did not change in any way. After some thinking I came up with the following interesting solution:

dispatch_async(mySerialQueue, ^{
+++dispatch_sync(dispatch_get_main_queue(), ^{
++++++// calculate value and update the GUI

So for every requested table row I add a new block to a queue that runs on a separate thread and processes its blocks in serial order. These blocks, processed on a separate thread, do just one thing: they add another block to the main queue and wait until this block is processed (dispatch_sync) before adding the next block. Finally these blocks, processed on the main thread, calculate the row values and update the GUI like before. Because of this transitions from the separate thread to the main thread, the main runloop gets a chance to process other events between every value calculation.

I find it interesting how much complicated work can be expressed in so few lines of code. Writing all this functionality “by hand” without using Grand Central Dispatch and Blocks would make it very complicated and probably less efficient.

CoreFoundation plus QuickTime on Windows

Monday, April 26th, 2010

We are writing portable cross-platform software, primarily running on Macs, Windows PCs, iPhones and iPads. Recently we had a problem to solve, that I’ll describe here.

Our code uses Apple’s CoreFoundation. On Mac OS X or iPhone OS it’s “just there” as part of the System Frameworks, and on Windows we use CoreFoundation in form of the great OpenCFLite port. Now we had a project where we’re also using Apple’s QuickTime. Again, on the Mac it’s “just there”, but on Windows we have to use the QuickTime SDK for Windows. Now when trying to build this project that uses both CoreFoundation and QuickTime on Windows, we got a lot of Linker errors complaining about duplicate symbols. The reason is that the QuickTime SDK for Windows itself contains its own subset of CoreFoundation. So we searched for a solution.

I already had the idea to write a wrapper around all necessary QuickTime calls and move this wrapper into a DLL to separate the QuickTime stuff from the main binary. So QuickTime called from the wrapper DLL uses its own embedded CoreFoundation implementation, and the main binary can still use OpenCFLite. Most probably there are some things to keep in mind, e.g. the API to the QuickTime wrapper must not pass any CoreFoundation objects across the boundary. CFStringRefs had to be passed e.g. as plain C strings UTF-8 encoded and the CFStringRef has then to be reconstructed from that inside the wrapper. But all this shouldn’t be much of a problem.

But we were not 100% sure if our theory really solves the problem, or wether there is an easier solution. Maybe some secret linking tricks or something like that.

We thought somebody else must already had the same problem!? And, yes, it came to my mind that the developers of WebKit – the engine of Apple’s web browser Safari – must have solved that. I know that WebKit uses CoreFoundation. And I also was pretty sure that WebKit uses QuickTime for displaying Video. Luckily WebKit is open source, so I downloaded the WebKit sources and digged into them to see if the WebKit engineers had the same problem and how they solved it.

Short time later I had the answer. Really, they obviously are in the same boat. And it was solved pretty much the same way as the idea that I already had in my mind. WebKit contains classes like “QTMovieWin” that are build into a separate DLL. So all QuickTime calls are done in those special wrapper classes from the DLL and WebKit itself does not directly call any QuickTime routines.

It’s always nice to see being not the only one having strange problems to solve. 😉

I published this article, because I googled a lot for CoreFoundation and QuickTime linking conflicts on Windows, but nobody seems to either have this constellation or did not write or ask about it. Maybe this article will help somebody out there …

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

#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.

Being Rejected. Not.

Thursday, March 12th, 2009

Here’s another story of an application being rejected by Apple from the App Store.

“Hey, you have an iPhone! – Can I take a look?”

Do you know that? This situation gave me the idea for a funny application that should display the Home screen of your iPhone or iPod touch, but as soon as someone touches it, a scary barking dog should appear. The idea for my little funny “Watchdog” application was born.

I developed it, polished it until I liked it much, wrote a description, created a web page etc. and finally submitted my iPhone application to Apple so they can review it and put it into their App Store.

Round One

On my first submitting attempt the Watchdog application contained real screenshots of the Home screen of the iPhone and the iPod touch in all available languages (blowing up the application size to about 7 MB). I already had the feeling that Apple will reject this because with the screenshots I indirectly use their icon graphics, but nevertheless I tried it. OK, my app really got rejected the first time.

Apple’s official answer was:

Unfortunately, your application, Watchdog Mobile, cannot be added to the App Store because it uses standard iPhone screen images in a non-standard way, potentially resulting in user confusion. Changing the behavior of standard iPhone graphics, actions, and images, or simulating failures of those graphics, actions, or images is a violation of the iPhone Developer Program agreement which requires applications to abide by the Human Interface Guidelines.

I can understand that Apple does not want screenshots of the Home screen in apps. The statement is still a bit strange, because Apple complains about “potentially resulting in user confusion”. Er … yes … indeed … Watchdog is designed to confuse (or surprise) the user! When someone uses Watchdog, he does it intentionally and after seeing the barking dog it should be obvious to everyone that there is a kind of … uhm … “watchdog” application running. It’s surprising and can be really shocking if you don’t reckon that (it actually happened to myself a few times) but it’s very funny and you realize the joke at the same second.

Round Two

OK, having screenshots of the Home screen containing Apple icons in an application is really a bad idea. So I added the ability to choose a custom image and wrote a description how the user can make a screenshot of his Home screen. Unfortunately this decreases the ease-of-use of the application a little bit, but it’s not really dramatic. I removed all bundled screenshots and created a funny comic styled “Fake Home screen” that is used as default image. As a side note, the size of the app reduced to around 1.5 MB.

But guess what … the second version of my application got rejected again. Apple’s statement was that “the modified iPhone screen image is still too similar to the iPhone screen image”. Argh. OK, I know there are different types of people … some are more “visual”, others are more “auditory” and others more “tactile” oriented. Maybe people that are not so “visual” may still confuse the comic styled Home screen with a real Home screen. By the way, I really like the big funny icons and once I saw them on the iPhone screen I wished they could be used for real. 😉

Round Three

I though about what I can use as default image instead. My first idea was to use a cute looking puppy. Perhaps with a sign around its neck saying something like “Replace me” or so. While this might be a bit funny, I did not want to get too far away from the original idea to present a Home screen. So I came up with a modified version of my comic styled Home screen: I dimmed it in brightness and put a very flashy text above it saying that it’s a Fake Home screen. So nobody can ever confuse this with a real Home screen. I was very curious about the reaction from Apple.

But – I was already prepared for that – Apple rejected it again. “Simulating failures” is obviously not accepted by Apple. At some degree I understand that, but I thought it’s obvious enough that no-one gets “potentially confused” by this application. Thought wrong.

Round Four

So I prepared my last attempt before giving up. I completely threw away the idea of simulating a Home screen. Let’s just make a dog application and let’s hope that the user has the idea of using a Home screen image for himself. I removed every comment about the Home screen from the application and its description. I replaced the Default image with a neat looking dog. I completely rewrote the description. There’s nothing of the original idea in this app. Of course, the user can still use a screenshot of the Home screen to have the original effect, but it’s not so obvious anymore. This time is took much longer for Apple to review this app … but finally …

Hooray – Apple accepted my Watchdog application! 🙂

Feel free to purchase Watchdog at the iPhone App Store and tell everybody how cool that thing can be used. 😉 Thank you very much for your support!

To get the best effect, you have to create a screenshot of your Home screen. This can be done by quickly pressing and releasing the Sleep/Wake and Home buttons at the same time while the Home screen is displayed. The screenshot ends up in the “Camera Roll” section of the Photo application on the iPhone. Then just choose this image in the Watchdog application. Have fun!

Finally a little gallery of the four different versions of the default image that I have created:

Evolution of the Default Image

Evolution of the Default Image