Objective-Cは、Rubyのようにメソッドの定義を書き換えたりする事ができます。

   1  #import <objc/runtime.h>
   2  
   3  id (*foo_without_bar)(id, SEL);
   4  id foo_with_bar(id self, SEL selector)
   5  {
   6    /* do your work here */
   7    return foo_without_bar(self, selector);
   8  }
   9  
  10  // exchange method implementation
  11  SEL fooSelector = @selector(foo);
  12  Method method = class_getInstanceMethod(class, fooSelector);
  13  *(IMP*)&foo_without_bar =
  14    method_getImplementation(method);
  15  method_setImplementation(method, (IMP)foo_with_bar);

この例では、IMPの定義と同じプロトタイプのメソッドを書き換えてるので不要ですが、IMPの定義と異なるプロトタイプのメソッドを書き換える場合は、 IMPにキャストする必要があります。

また、戻り値が浮動小数型であったり、サイズが大きい構造体を返すメソッドの場合は、上記の例とは異なる方法を使う必要があるので、注意が必要です。(NSInvocationを使う必要があります)

See Also

posted by Png genki on Fri 7 Nov 2008 at 12:00 with 2 comments

Comments:

Png 瀧内元気 over 15 years ago.

fooSelectorがfooになってたので訂正。

Png 瀧内元気 over 15 years ago.

Objective-Cの流儀ではMethod Swizzlingと呼ぶらしい。

or Preview
Social Bookmarks
  • Delicious
  • B_entry1008
  • Clip_16_12_w
Services from s21g
twpro(ツイプロ)
Twitterプロフィールを快適検索
地価2009
土地の値段を調べてみよう
MyRestaurant
自分だけのレストラン手帳
Formula
ブログに数式を埋め込める数式コミュニティ