SEL is a type that represents a selector in Objective-C. The @selector() keyword returns a SEL that you describe. It's not a function pointer and you can't pass it any objects or references of any kind. For each variable in the selector (method), you have to represent that in the call to @selector. For example:
-(void)methodWithNoArguments; SEL noArgumentSelector =@selector(methodWithNoArguments);
-(void)methodWithOneArgument:(id)argument; SEL oneArgumentSelector =@selector(methodWithOneArgument:);// notice the colon here注意引号
-(void)methodWIthTwoArguments:(id)argumentOne and:(id)argumentTwo; SEL twoArgumentSelector =@selector(methodWithTwoArguments:and:);// notice the argument names are omitted
Selectors are generally passed to delegate methods and to callbacks to specify which method should be called on a specific object during a callback.
一个计时器的例子:@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; }
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)seconds target:(id)target selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)repeat
这个是NSTimer里的方法;
这句代码的意思就是每隔30s会调用selector 代表的方法(回调方法)myTimerCallback;
你可以理解 @selector()就是取类方法的编号,他的行为基本可以等同C语言的中函数指针,但不是指针,只不过C语言中,可以把函数名直接赋给一个函数指针,而Objective-C的类不能直接应用函数指针,这样只能做一个@selector语法来取.