使用参数从方法名称创buildselect器

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

 SEL callback = @selector(mymethod:parameter2); 

我有一个方法

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

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

我努力了:

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

但它不会编译。

SEL是一个代表Objective-C中select器的types。 @selector()关键字返回一个你描述的SEL。 这不是一个函数指针,你不能传递任何对象或任何types的引用。 对于select器(方法)中的每个variables,必须在对@selector的调用中表示该variables。 例如:

 -(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 

select器通常传递给委托方法和callback来指定在callback期间应该在特定对象上调用哪个方法。 例如,当你创build一个计时器时,callback方法被明确定义为:

 -(void)someMethod:(NSTimer*)timer; 

所以当你计划定时器时,你可以使用@selector来指定你的对象上的哪个方法实际上将负责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; } 

在这种情况下,您正在指定每隔30秒用myTimerCallback向对象obj发送消息。

您不能在@selector()中传递参数。

看起来你试图实现一个callback。 最好的办法是这样的:

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

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

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

除了已经说过的关于select器,你可能想看看NSInvocation类。

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

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

请记住,虽然它在某些情况下很有用,但是在正常的编码date中不要使用NSInvocation。 如果你只是想让两个对象相互交谈,可以考虑定义一个非正式或正式的委托协议,或者像前面提到的那样传递一个select器和目标对象。