Objective-Cは、Rubyのようにメソッドの定義を書き換えたりする事ができます。
objective-c>>
#import <objc/runtime.h>
id (foo_without_bar)(id, SEL);
id foo_with_bar(id self, SEL selector)
{
/ do your work here */
return foo_without_bar(self, selector);
}
// exchange method implementation
SEL fooSelector = @selector(foo);
Method method = class_getInstanceMethod(class, fooSelector);
(IMP)&foo_without_bar =
method_getImplementation(method);
method_setImplementation(method, (IMP)foo_with_bar);
<<--
この例では、IMPの定義と同じプロトタイプのメソッドを書き換えてるので不要ですが、IMPの定義と異なるプロトタイプのメソッドを書き換える場合は、
IMPにキャストする必要があります。
また、戻り値が浮動小数型であったり、サイズが大きい構造体を返すメソッドの場合は、上記の例とは異なる方法を使う必要があるので、注意が必要です。(NSInvocationを使う必要があります)
See Also
posted by
genki on Fri 7 Nov 2008 at 11:42 with 2 comments