将方法作为参数传递

发布于 2024-12-10 00:12:14 字数 448 浏览 5 评论 0原文

我可以传递一个方法作为参数吗? 在下面的示例中,我没有成功传递 targetOpenView 方法:

-(void) targetTimeView:(id)sender {    
[self TimeViewWithtimeInterval:.6 selector:targetOpenView]; //targetOpenView does NOT work
}

-(void) timeViewWithtimeInterval:(float)interval selector:openViewMethod{
[NSTimer scheduledTimerWithTimeInterval:interval target:self selector:@selector(openViewMethod) userInfo:nil repeats:NO];   
}

有什么建议可以让我完成这项工作吗?谢谢!

can I pass a method as an argument?
I don't succeed to pass the method targetOpenView in the example below:

-(void) targetTimeView:(id)sender {    
[self TimeViewWithtimeInterval:.6 selector:targetOpenView]; //targetOpenView does NOT work
}

-(void) timeViewWithtimeInterval:(float)interval selector:openViewMethod{
[NSTimer scheduledTimerWithTimeInterval:interval target:self selector:@selector(openViewMethod) userInfo:nil repeats:NO];   
}

Any suggestions how I could make this work? Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

没有你我更好 2024-12-17 00:12:14

您需要 @selector 编译器指令从方法名称中提取选择,就像创建计时器时所做的那样:

[self TimeViewWithtimeInterval:.6 selector:@selector(targetOpenView)];

并将参数定义为类型 SEL

-(void) TimeViewWithtimeInterval:(float)interval selector:(SEL)openViewMethod
{    
 ...
}

然后,当将参数传递给 NSTimer 方法,您可以省略 @selector 因为该类型已经是一个选择器:

[NSTimer scheduledTimerWithTimeInterval:interval target:self
                               selector:@selector(openViewMethod) /* here */
                               userInfo:nil repeats:NO];   

[NSTimer scheduledTimerWithTimeInterval:interval target:self
                               selector:openViewMethod /* pass it directly */
                               userInfo:nil repeats:NO];

You need the @selector compiler directive to extract the select from a method name, like you did when creating the timer:

[self TimeViewWithtimeInterval:.6 selector:@selector(targetOpenView)];

And define your argument to the type SEL:

-(void) TimeViewWithtimeInterval:(float)interval selector:(SEL)openViewMethod
{    
 ...
}

Then, when passing the argument to the NSTimer method you can leave off the @selector since the type is already a selector:

[NSTimer scheduledTimerWithTimeInterval:interval target:self
                               selector:@selector(openViewMethod) /* here */
                               userInfo:nil repeats:NO];   

[NSTimer scheduledTimerWithTimeInterval:interval target:self
                               selector:openViewMethod /* pass it directly */
                               userInfo:nil repeats:NO];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文