我有一个从当前对象获取SEL的代码示例

SEL callback = @selector(mymethod:parameter2);

我有一个像

这样的方法
 -(void)mymethod:(id)v1 parameter2;(NSString*)v2 {
}

现在我需要将mymethod移动到另一个对象,比如myDelegate

我试过了:

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

但它不会编译。

有帮助吗?

解决方案

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

其他提示

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

看起来您正在尝试实施回调。最好的方法是:

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

然后在你的对象的setCallbackObject:withSelector:方法:你可以调用你的回调方法。

-(void)setCallbackObject:(id)anObject withSelector:(SEL)selector {
    [anObject performSelector:selector];
}

除了已经有关选择器的说法之外,你可能想看一下NSInvocation类。

  

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

     

NSInvocation对象包含Objective-C消息的所有元素:目标,选择器,参数和返回值。可以直接设置这些元素中的每一个,并在调度NSInvocation对象时自动设置返回值。

请记住,虽然它在某些情况下很有用,但您不会在正常的编码日使用NSInvocation。如果您只是想让两个对象相互通信,请考虑定义一个非正式或正式的委托协议,或者如已经提到的那样传递一个选择器和目标对象。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top