开发者

Pass method as argument

开发者 https://www.devze.com 2023-04-13 00:36 出处:网络
can I 开发者_Python百科pass a method as an argument? I don\'t succeed to pass the method targetOpenView in the example below:

can I 开发者_Python百科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!


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];
0

精彩评论

暂无评论...
验证码 换一张
取 消