问题描述
我有一个代码示例,可从当前对象
I have a code sample that gets a SEL
from the current object,
SEL callback = @selector(mymethod:parameter2);
我有一个类似
-(void)mymethod:(id)v1 parameter2;(NSString*)v2 {
}
现在我需要将mymethod
移动到另一个对象,例如myDelegate
.
Now I need to move mymethod
to another object, say myDelegate
.
我尝试过:
SEL callback = @selector(myDelegate, mymethod:parameter2);
但是不会编译.
推荐答案
SEL是表示Objective-C中选择器的一种类型. @selector()关键字返回您描述的SEL.它不是函数指针,您不能将任何对象或任何类型的引用传递给它.对于选择器中的每个变量(方法),必须在对@selector的调用中表示该变量.例如:
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)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
选择器通常传递给委托方法和回调,以指定在回调期间应在特定对象上调用哪个方法.例如,当您创建计时器时,回调方法专门定义为:
Selectors are generally passed to delegate methods and to callbacks to specify which method should be called on a specific object during a callback. For instance, when you create a timer, the callback method is specifically defined as:
-(void)someMethod:(NSTimer*)timer;
因此,当您安排计时器时,您将使用@selector来指定对象上的哪个方法实际上将负责回调:
So when you schedule the timer you would use @selector to specify which method on your object will actually be responsible for the 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发送消息.
In this case you are specifying that the object obj be messaged with myTimerCallback every 30 seconds.
这篇关于从带有参数的方法名称创建选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!