2011年11月27日日曜日

IMP, SEL, Method

IMP
まず IMP です。メソッド実装の先頭部分を指すポインタです。

This data type is a pointer to the start of the function that implements the method. This function uses standard C calling conventions as implemented for the current CPU architecture. The first argument is a pointer to self (that is, the memory for the particular instance of this class, or, for a class method, a pointer to the metaclass). The second argument is the method selector. The method arguments follow.
IMP はメソッドを実装する関数の先頭部分を指すポインタです。この関数は現在の CPU アーキテクテャのために実装された標準 C の呼出規約(calling convention)を使います。最初の引数は self(クラスの特定の具体的なインスタンスのためのメモリ、クラスメソッドのためのメモリ、メタクラスを指すポインタのためのメモリ)へのポインタです。2番目の引数はメソッドセレクタです。メソッドの引数は以下の通り。


SEL
そして SEL です。セレクタを表現する構造体で Opaque Type です。

Method selectors are used to represent the name of a method at runtime. A method selector is a C string that has been registered (or “mapped“) with the Objective-C runtime. Selectors generated by the compiler are automatically mapped by the runtime when the class is loaded.

You can add new selectors at runtime and retrieve existing selectors using the function sel_registerName.

When using selectors, you must use the value returned from sel_registerName or the Objective-C compiler directive @selector(). You cannot simply cast a C string to SEL.
メソッドのセレクタはランタイムでメソッドの名前表現として使われます。メソッドのセレクタは Objective-C に登録(またはマッピング)されている C 文字列です。コンパイラによって生成されたセレクタは、クラスがロードされるとき、自動的にランタイムによってマッピングされます。

実行時に新しいセレクタを追加し、sel_registerName 関数を使って存在しているセレクタを取得できます。

セレクタを使うとき、sel_registerName が返す値か、Objective-C のコンパイラディレクティブ @selector() を使わなければなりません。単純に C 文字列を SEL にキャストすることはできません。


Method
Method はクラスで定義されているメソッドを表現する構造体で Opaque Type です。リファレンスには

typedef struct objc_method *Method;
としかありませんが runtime.h にはさらに
struct objc_method {
    SEL method_name                                          OBJC2_UNAVAILABLE;
    char *method_types                                       OBJC2_UNAVAILABLE;
    IMP method_imp                                           OBJC2_UNAVAILABLE;
}
とあります。OBJC2_UNAVAILABLE は Objective-C 2.0 では無効ということのようで、Objective-C 2.0 の環境ではこの構造体に直接アクセスはできません。Method 構造体にのデータにアクセスするには専用(method_*)のランタイム関数を使ってやればよしです。

めも
http://opensource.apple.com/

0 件のコメント:

コメントを投稿