2008-11-18 32 views
53

我有一个代码示例,会从当前对象的SEL创建从一个方法名称的选择与参数

SEL callback = @selector(mymethod:parameter2); 

而且我有喜欢

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

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

我曾尝试:

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

,但它不会编译。

+2

@Jim Puls--这实际上是一个Objective-C问题......对于可可或Cocoa-touch而言,它并不是特定于iPhone-sdk。此外,我们正在与objectivec标签这些天:)目标c :) – 2008-11-18 02:57:28

回答

95

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

16

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

它看起来像你试图实现回调。要做到这一点,最好的办法是这样的:

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

然后在你的对象setCallbackObject:withSelector:方法:你可以打电话给你的回调方法。

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

这也不是纯粹的iPhone。您可能想阅读Apple的文档“Obective-C 2.0编程语言”,可以在这里找到http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC/Introduction/chapter_1_section_1.html – 2008-11-18 02:43:10

+4

要调用选择器需要调用: [anObject performSelector:selector]; – 2009-07-23 19:42:20

5

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

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

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

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

相关问题