zoukankan      html  css  js  c++  java
  • Objective C SEl 和@selector是怎么工作的||How do SEL and @selector work in iphone sdk?

    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语法来取.
  • 相关阅读:
    ubuntu环境下eclipse的安装以及hadoop插件的配置
    hadoop启动步骤
    Ubuntu下hadoop环境的搭建(伪分布模式)
    volatile关键字作用
    CyclicBarrier&CountDownLatch&Semaphore
    Callable、Future和FutureTask浅析
    Unsafe与CAS
    接口和抽象类的区别
    内部类
    泛型
  • 原文地址:https://www.cnblogs.com/fengjian/p/3310111.html
Copyright © 2011-2022 走看看