代码之家  ›  专栏  ›  技术社区  ›  BlueDolphin

从带有参数的方法名称创建选择器

  •  57
  • BlueDolphin  · 技术社区  · 17 年前

    SEL 从当前对象,

    SEL callback = @selector(mymethod:parameter2);
    

    我有一个方法,比如

     -(void)mymethod:(id)v1 parameter2;(NSString*)v2 {
    }
    

    现在我得走了 mymethod myDelegate .

    我试过:

    SEL callback = @selector(myDelegate, mymethod:parameter2);
    

    3 回复  |  直到 12 年前
        1
  •  102
  •   erkanyildiz    9 年前

    SEL是表示Objective-C中选择器的类型。@selector()关键字返回您描述的SEL。它不是函数指针,您不能向它传递任何对象或任何类型的引用。对于选择器(方法)中的每个变量,必须在对@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
    

    -(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发送一次消息。

        2
  •  18
  •   grahamparks    15 年前

    无法在@selector()中传递参数。

    [object setCallbackObject:self withSelector:@selector(myMethod:)];
    

    -(void)setCallbackObject:(id)anObject withSelector:(SEL)selector {
        [anObject performSelector:selector];
    }
    
        3
  •  5
  •   Community Mohan Dere    6 年前

    除了已经说过的选择器之外,您可能还想看看NSInvocation类。

    NSInvocation是一个呈现为静态的Objective-C消息,也就是说,它是一个转化为对象的操作。NSInvocation对象主要由NSTimer对象和分布式对象系统用于在对象之间和应用程序之间存储和转发消息。

    请记住,虽然它在某些情况下很有用,但在正常的编码过程中不使用NSInvocation。如果你只是试图让两个对象互相交谈,考虑定义一个非正式的或正式的委托协议,或者传递一个选择器和目标对象,如已经提到的。