SELは、Objective-Cのセレクターを表すタイプです。@selector()キーワードは、記述したSELを返します。これは関数ポインタではなく、オブジェクトや参照を渡すことはできません。セレクター(メソッド)の変数ごとに、@selectorの呼び出しでそれを表す必要があります。例えば:
-(void)methodWithNoParameters;
SEL noParameterSelector = @selector(methodWithNoParameters);
-(void)methodWithOneParameter:(id)parameter;
SEL oneParameterSelector = @selector(methodWithOneParameter:); // notice the colon here
-(void)methodWIthTwoParameters:(id)parameterOne and:(id)parameterTwo;
SEL twoParameterSelector = @selector(methodWithTwoParameters:and:); // notice the parameter names are omitted
セレクターは通常、デリゲートメソッドとコールバックに渡され、コールバック中に特定のオブジェクトで呼び出されるメソッドを指定します。たとえば、タイマーを作成する場合、コールバックメソッドは具体的に次のように定義されます。
-(void)someMethod:(NSTimer*)timer;
したがって、タイマーをスケジュールするときは、@ selectorを使用して、オブジェクトのどのメソッドが実際にコールバックを担当するかを指定します。
@implementation MyObject
-(void)myTimerCallback:(NSTimer*)timer
{
// do some computations
if( timerShouldEnd ) {
[timer invalidate];
}
}
@end
// ...
int main(int argc, const char **argv)
{
// do setup stuff
MyObject* obj = [[MyObject alloc] init];
SEL mySelector = @selector(myTimerCallback:);
[NSTimer scheduledTimerWithTimeInterval:30.0 target:obj selector:mySelector userInfo:nil repeats:YES];
// do some tear-down
return 0;
}
この場合、オブジェクトobjが30秒ごとにmyTimerCallbackでメッセージを送信されるように指定しています。