My Higher Order Message Implementation

Note: This is not an original idea of mine.  For a good explanation of what Higher Order Messaging is, see this paper.

The Idea

There are some great implementations of higher order messaging, but this is not one of them.  Instead, this is an implementation of a HigherOrderMessage object, which is designed with the goal of extensibility, by forgoing subclasses for blocks.  This is obviously very straight forward, with an external interface of just

+ (id)HOMWithGetSignatureForSelector:(NSMethodSignature *(^)(SEL selector))_sig
                             capture:(void (^)(NSInvocation *message))_forward

This way, we can put all of the higher order messaging logic in one place, allowing us to (for example) implement -[NSObject(HOM) ifResponds] in only 7 lines:

- (id)ifResponds {
	return [HigherOrderMessage HOMWithGetSignatureForSelector:^(SEL selector) {
		return [self methodSignatureForSelector:selector] ?: [NSMethodSignature signatureWithObjCTypes:"@@:"];
	} capture:^(NSInvocation *message) {
		[message invokeWithTarget:([self respondsToSelector:message.selector] ? self : nil)];

Note that for selectors which are not understood, if the calling function expects a non-object/pointer return type, this may produce undefined returns.  However, this post is about the HigherOrderMessage, so the details of various calling conventions will be left to others, except for this reminder that whenever we deal with NSMethodSignature and NSInvocation we need to pay extra close attention, as these are relatively fragile as Cocoa classes go (of no fault of their own).

The Implementation

At any rate, the implementation for this is extremely simple: create ivars for the two blocks, and call them in -methodSignatureForSelector: and -forwardInvocation: respectively.  First instinct is to put these in a subclass of NSProxy, considering that’s its raison d’être. However, NSProxy implements a number of methods which we would naturally prefer forwarded to our target, for example -class, to which NSProxy responds with its own subclass, as opposed to the class of the target.

Instead, we can easily implement our own root class, with only two things the language requires for all classes: have the first ivar be a Class, commonly named isa (for is-a, as in this object is-a whatever-class-this-first-ivar-is), and implement +initialize, because +initialize is called just before the first message is sent to an object of its class, and we therefore crash without it.  (note: class_createInstance and later object_dispose used in place of +alloc and -dealloc respectively are defined in <objc/runtime.h>, so you’ll need to #include it in HigherOrderMessage.m)

@interface HigherOrderMessage {
	Class isa;
	NSUInteger retainCount;

	NSMethodSignature *(^methodSignatureForSelector)(SEL selector);
	void (^forward)(NSInvocation *capture);
+ (id)HOMWithGetSignatureForSelector:(NSMethodSignature *(^)(SEL selector))_sig
			     capture:(void (^)(NSInvocation *message))_forward;
- (id)retain;
- (id)autorelease;
- (void)release;
+ (id)HOMWithGetSignatureForSelector:(NSMethodSignature *(^)(SEL selector))_sig
			     capture:(void (^)(NSInvocation *message))_forward
	HigherOrderMessage *message = class_createInstance(self, 0);
	if (message) {
		message->methodSignatureForSelector = [_sig copy];
		message->forward = [_forward copy];
		message->retainCount = 1;
	return [message autorelease];

- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
	return methodSignatureForSelector(aSelector);

- (void)forwardInvocation:(NSInvocation *)invocation {

+ (void)initialize {

Memory Management

One other thing NSProxy takes care of (also the main reason for choosing it over making a root class) is memory management: it implements +alloc, -retain, -release, -autorelease, and -dealloc.   These are not only easy to avoid/implement, but in the off chance that -dealloc is to be called directly by a client of a HigherOrderMessage, it would almost definitely be intended for the forwarding target, so by not using NSProxy, we can simply not implement -dealloc on HigherOrderMessage, and instead put the teardown logic in -release.  Indeed, this makes sense when we look at -dealloc as simply an override point called in the default -release implementation so that typically we do not have to override it.

We will use the __sync_add_and_fetch and __sync_sub_and_fetch functions for incrementing and decrementing the retainCount because they are GCC atomic builtins, making -retain and -release thread safe, as long as the memory management guide is adhered to.  Of course, in -release when the retain count hits zero but the object has not yet been disposed, if another thread calls -forwardInvocation: or -methodSignatureForSelector: it would cause a dereference of the then-deallocated block called in that method, and thus a crash.  There’s no point in trying to change this, as this is how Cocoa handles it, with the same problems.  However, the memory management guide says that no pointers should be left pointing at an object when it is destroyed, so no methods could be called on it, making this potential race condition theoretically impossible.

- (id)retain {
	__sync_add_and_fetch(&retainCount, 1);
	return self;

- (id)autorelease {
	[NSAutoreleasePool addObject:self];
	return self;

- (void)release {
	if (__sync_sub_and_fetch(&retainCount, 1) == 0) {
		[methodSignatureForSelector release];
		[forward release];



Higher Order Messaging is very cool, and very powerful, but one thing annoying about implementing it is the excessive use of subclasses in addition to NSObject/collection class categories, which breaks up the logic into  two places.  My particular implementation uses blocks, which in many ways can be used in place of Higher Order Messaging, to implement said higher order messaging, while alleviating the issues of separation of logic, and allowing it to be instead encapsulated in the implementation of the (category) method.

You can download the project at