NSInvocations zusammenbauen...

written by Martin Häcker on

...ist deutlich schmerzhaft.

Man muss eine Menge Aufwand treiben um aus einem objc-call etwas zu machen dass man schön hin und her passen kann.

Zum Beispiel:

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    id aString = @"fnord";

    id signature = [aString methodSignatureForSelector:@selector(stringByAppendingString:)];
    id invocation = [NSInvocation invocationWithMethodSignature:signature];

    [invocation setTarget:aString];
    [invocation setSelector:@selector(stringByAppendingString:)];
    id appender = @"23";
    [invocation setArgument:&appender atIndex:2];

    [invocation invoke];

    id returnValue = nil;
    [invocation getReturnValue:&returnValue];

    NSLog(@"Got: %@", returnValue);

    [pool drain];
    return 0;
}

Das nervt sobald man es öfters als einmal machen muss.

Darum hab ich mir nach langem nachdenken mal etwas zusammengebaut das das erleichtert. Es ist nicht perfekt und ich hab auch eine Menge Ideen wie man es noch schöner machen kann, aber es funktioniert. :)

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    id invocation = NMCatchInvocation(@"fnord", stringByAppendingString:@"23");

    [invocation invoke];

    id returnValue = nil;
    [invocation getReturnValue:&returnValue];

    NSLog(@"Got: %@", returnValue);

    [pool drain];
    return 0;
}

Und das sieht schon bedeutend besser aus.

  • [source:open-source/NMInvocationBuilder/trunk Hier gehts zum Code]