Objective-
1 #import <objc/runtime.h> 2 3 id (*foo_withou t_bar)(id, SEL); 4 id foo_with_b ar(id self, SEL selector) 5 { 6 /* do your work here */ 7 return foo_withou t_bar(self, selector); 8 } 9 10 // exchange method implementa tion 11 SEL fooSelecto r = @selector(foo); 12 Method method = class_getI nstanceMet hod(class, fooSelecto r); 13 *(IMP*)&foo_withou t_bar = 14 method_get Implementa tion(method); 15 method_set Implementa tion(method, (IMP)foo_with_b ar);
この例では、IMPの定義と同じプロトタイプのメソッドを書き換えてるので不要ですが、IMPの定義と異なるプロトタイプのメソッドを書き換える場合は、 IMPにキャストする必要があります。
また、戻り値が浮動小数型であったり、サイズが大きい構造体を返すメソッドの場合は、上記の例とは異なる方法を使う必要があるので、注意が必要です。(NSInvocati
See Also
posted by
genki
on Fri 7 Nov 2008
at 12:00
with
2 comments
fooSelectorがfooになってたので訂正。
Objective-Cの流儀ではMethod Swizzlingと呼ぶらしい。