我有一个调用方法的定时器,但是这个方法需要一个参数:
theTimer = [NSTimer scheduledTimerWithTimeInterval:animationInterval target:self selector:@selector(timer) userInfo:nil repeats:YES];
应该是
theTimer = [NSTimer scheduledTimerWithTimeInterval:animationInterval target:self selector:@selector(timer:game) userInfo:nil repeats:YES];
现在这个语法似乎不对。我尝试使用 NSInvocation 但我遇到了一些问题:
timerInvocation = [NSInvocation invocationWithMethodSignature:
[self methodSignatureForSelector:@selector(timer:game)]];
theTimer = [NSTimer scheduledTimerWithTimeInterval:animationInterval
invocation:timerInvocation
repeats:YES];
我应该如何使用调用?
最佳答案
给出这个定义:
- (void)timerFired:(NSTimer *)timer
{
...
}
然后您需要使用 @selector(timerFired:)
(这是方法名称,没有任何空格或参数名称,但包括冒号)。您要传递的对象 (game
?) 通过 userInfo:
部分传递:
theTimer = [NSTimer scheduledTimerWithTimeInterval:animationInterval
target:self
selector:@selector(timerFired:)
userInfo:game
repeats:YES];
在您的计时器方法中,您可以通过计时器对象的 userInfo
方法访问此对象:
- (void)timerFired:(NSTimer *)timer
{
Game *game = [timer userInfo];
...
}
关于objective-c - 如何将参数传递给 NSTimer 中调用的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5166171/