我可以将方法作为参数传递吗? 我没有成功传递下面示例中的方法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];
}
有什么建议我可以做这个工作吗?谢谢!
答案 0 :(得分:6)
您需要@selector
编译器指令从方法名称中提取select,就像创建计时器时一样:
[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];