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语法来取.
  • 相关阅读:
    junit源码解析--测试驱动运行阶段
    junit源码解析--初始化阶段
    junit源码解析--核心类
    junit测试套件
    junit参数化测试
    junit忽略测试方法
    Junit4常用注解
    泛型技术
    在使用Java8并行流时的问题分析
    Linux 常用性能分析命令
  • 原文地址:https://www.cnblogs.com/fengjian/p/3310111.html
Copyright © 2011-2022 走看看