Skip to content

Instantly share code, notes, and snippets.

@boucher
Created August 16, 2009 19:44
Show Gist options
  • Select an option

  • Save boucher/168735 to your computer and use it in GitHub Desktop.

Select an option

Save boucher/168735 to your computer and use it in GitHub Desktop.
@import <Foundation/CPObject.j>
// bad class name. need something better.
@implementation CPFunctionForwarder : CPObject
{
CPDictionary _implementations;
}
- (id)init
{
if (self = [super init])
_implementations = [CPDictionary dictionary];
return self;
}
// used like this:
// [CPFunctionForwarder objectWithFunctionsForSelectors:
// function(self, cmd, foo, bar, baz) {},
// @"methodWithParameter:andAnother:lastOne:"];
//
// obviously, you can respond to as many selectors as you like
// debatable whether or not to strip self and cmd from the params
+ (id)objectWithFunctionsForSelectors:(id)anObject,...
{
var object = [[self alloc] init];
for(var i = 2; i < arguments.length; i+=2)
{
var selector = arguments[i],
implementation = arguments[i+1];
if (!selector || !implementation)
break;
[_implementations setValue:implementation forKey:selector];
}
return object;
}
- (void)forwardInvocation:(CPInvocation)anInvocation
{
var implementation = [_implementations objectForKey:[anInvocation selector]];
if (implementation)
{
var returnValue = implementation.apply(self, [anInvocation arguments]);
[anInvocation setReturnValue:returnValue];
}
else
[super forwardInvocation:anInvocation];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment