objective-c - 如何将参数传递给 NSTimer 中调用的方法

标签 objective-c arguments nstimer nsinvocation

我有一个调用方法的定时器,但是这个方法需要一个参数:

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/

相关文章:

ios - Objective-C :带有 UIImage 的 PushViewController 不工作

objective-c - 核心数据未正确重置数据库

python - 以编程方式加载 Python 模块/函数

javascript - 如何最好地确定参数是否未发送到 JavaScript 函数

ios - 在 iPhone 上刷新数据导致系统变得不稳定或无响应

使用 NSTimer 通过单元测试后,iOS 逻辑单元测试目标崩溃

ios - 当我呈现另一个 View Controller 时,NSTimer 不会停止

ios - didSelectRowAtIndexPath 不适用于 NSNotificationCenter

javascript - 与命名箭头函数中的arguments.length混淆

r - 如何访问函数参数的默认值?