6

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

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

我应该如何使用调用?

4

3 回答 3

11

鉴于此定义:

- (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];
    ...
}
于 2011-03-02T10:41:47.350 回答
6

正如@DarkDust 指出的那样,NSTimer期望其目标方法具有特定的签名。如果由于某种原因您不能遵守,您可以NSInvocation按照您的建议使用 an ,但在这种情况下,您需要使用选择器、目标和参数完全初始化它。例如:

timerInvocation = [NSInvocation invocationWithMethodSignature:
                   [self methodSignatureForSelector:@selector(methodWithArg1:and2:)]];

// configure invocation
[timerInvocation setSelector:@selector(methodWithArg1:and2:)];
[timerInvocation setTarget:self];
[timerInvocation setArgument:&arg1 atIndex:2];   // argument indexing is offset by 2 hidden args
[timerInvocation setArgument:&arg2 atIndex:3];

theTimer = [NSTimer scheduledTimerWithTimeInterval:animationInterval
                                        invocation:timerInvocation
                                           repeats:YES];

单独调用invocationWithMethodSignature并不能完成所有这些,它只是创建一个能够以正确方式填充的对象。

于 2011-03-02T11:04:11.320 回答
2

您可以通过这样的参数传递NSDictionary命名对象(如myParamName => myObjectuserInfo

theTimer = [NSTimer scheduledTimerWithTimeInterval:animationInterval 
                                            target:self 
                                          selector:@selector(timer:) 
                                          userInfo:@{@"myParamName" : myObject} 
                                           repeats:YES];

然后在timer:方法中:

- (void)timer:(NSTimer *)timer {
    id myObject = timer.userInfo[@"myParamName"];
    ...
}
于 2011-03-02T10:42:33.333 回答