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

标签 objective-c selector

我有一个从当前对象获取 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

选择器通常传递给委托(delegate)方法和回调,以指定在回调期间应在特定对象上调用哪个方法。例如,当你创建一个定时器时,回调方法具体定义为:

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

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

关于objective-c - 从带有参数的方法名称创建选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/297680/

相关文章:

ios - 在后台运行 ios 应用程序

css - Chrome 等效于 Firefox Firebug CSS 选择路径

iPhone:IBAction 导致 "Unrecognized Selector Sent to Instance"错误

ios - UIImageView 旋转后高宽变化

ios - ScrollView 类 iOS

ios - NSMutableArray count 说只有一个元素在里面,其实它们更多

ios - 在 objective-c 中的方法之间传递值

Swift #selector 问题

javascript - 如何通过 JavaScript 在属性之前应用 css?

ios - 无法识别的选择器发送到实例 - Swift 3