凌动小生的Blog

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
  101 随笔 :: 1 文章 :: 2 评论 :: 88962 阅读
< 2025年1月 >
29 30 31 1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31 1
2 3 4 5 6 7 8

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:

1
2
3
4
-(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语法来取.
posted on   凌动小生  阅读(308)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示