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

Mic*_*ele 6 arguments objective-c nstimer nsinvocation

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

theTimer = [NSTimer scheduledTimerWithTimeInterval:animationInterval target:self selector:@selector(timer) userInfo:nil repeats:YES];
Run Code Online (Sandbox Code Playgroud)

应该

theTimer = [NSTimer scheduledTimerWithTimeInterval:animationInterval target:self selector:@selector(timer:game) userInfo:nil repeats:YES];
Run Code Online (Sandbox Code Playgroud)

现在这种语法似乎不对.我试过NSInvocation但我遇到了一些问题:

timerInvocation = [NSInvocation invocationWithMethodSignature:
        [self methodSignatureForSelector:@selector(timer:game)]];

theTimer = [NSTimer scheduledTimerWithTimeInterval:animationInterval
        invocation:timerInvocation
        repeats:YES];
Run Code Online (Sandbox Code Playgroud)

我该如何使用Invocation?

Dar*_*ust 11

鉴于此定义:

- (void)timerFired:(NSTimer *)timer
{
   ...
}
Run Code Online (Sandbox Code Playgroud)

然后你需要使用@selector(timerFired:)(这是方法名称,没有任何空格或参数名称,但包括冒号).要传递的对象(game?)通过userInfo:部件传递:

theTimer = [NSTimer scheduledTimerWithTimeInterval:animationInterval 
                                            target:self 
                                          selector:@selector(timerFired:) 
                                         userInfo:game
                                          repeats:YES];
Run Code Online (Sandbox Code Playgroud)

在您的计时器方法中,您可以通过计时器对象的userInfo方法访问此对象:

- (void)timerFired:(NSTimer *)timer
{
    Game *game = [timer userInfo];
    ...
}
Run Code Online (Sandbox Code Playgroud)


wal*_*lky 5

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

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];
Run Code Online (Sandbox Code Playgroud)

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