at_yasu's blog

ロード的なことを

method_exchangeImplementations

method_exchangeImplementationsをすると、メソッドをオーバーライトっぽい事をする。

#import <Cocoa/Cocoa.h>
#import <objc/runtime.h>

@interface test : NSObject
{}
@end

@implementation test
- (void) loadTest
{
	NSLog(@"test::loadTest");
}

- (void) loadTestNew
{
	[self loadTestNew];
	NSLog(@"test::loadTestNew");
}
@end


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

	Class t = objc_getClass("test");
	Method old = class_getInstanceMethod(t, @selector(loadTest));
	Method new = class_getInstanceMethod(t, @selector(loadTestNew));
	method_exchangeImplementations(old, new);
	
	test *f = [t new];
	[f loadTest];
	[f release];

	[pool release];
}

コンパイル結果

[yasui@MacMini: ~/tmp/methodExchangeTest][13:36] $ gcc -o test testclass.m -Wall -framework Foundation -lobjc
testclass.m: In function ‘main’:
testclass.m:38: warning: control reaches end of non-void function
[yasui@MacMini: ~/tmp/methodExchangeTest][13:36] $ ./test
2009-06-22 13:36:56.531 test[469:807] test::loadTest
2009-06-22 13:36:56.533 test[469:807] test::loadTestNew
[yasui@MacMini: ~/tmp/methodExchangeTest][13:36] $