SEL是Objective-C中表示 Select 器的类型.@selector()关键字返回您描述的SEL.它不是函数指针,不能传递任何对象或任何类型的引用.对于 Select 器(方法)中的每个变量,必须在对@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
Select 器通常被传递给委托方法和回调,以指定在回调期间应该对特定对象调用哪个方法.例如,创建计时器时,回调方法的具体定义如下:
-(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;
}
在本例中,您指定每隔30秒用myTimerCallback向对象obj发送一次消息.