Objective-C で AUTOLOAD (あるいは method_missing )

forwardInvocation とかを使えば出来るみたい。

#import <Foundation/Foundation.h>

@interface Foo : NSObject;
-(void)call:(NSString*)sel;
@end

@implementation Foo

-(void)call:(NSString*)sel {
    NSLog(@"call: %@", sel);
}

-(void)forwardInvocation:(NSInvocation *)invocation {
    [self call:NSStringFromSelector([invocation selector])];
}

-(NSMethodSignature*)methodSignatureForSelector:(SEL)sel {
    NSMethodSignature* sig = [super methodSignatureForSelector:sel];
    if (sig) return sig;

    return [[self class] instanceMethodSignatureForSelector:@selector(call:)];
}

@end

int main() {
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];

    Foo* foo = [[Foo alloc] init];

    [foo bar];
    [foo buzz];

    [foo release];

    [pool drain];
    return 0;
}

// gcc -framework Foundation foo.m

詳細は Objective-C Runtime Programming Guide にある。

by typester / at 2011-12-05T20:32:00 / iphone · objc / Comments(0)