2011-03-02 50 views
6

我有一个计时器调用一个方法,但这种方法需要一个paramether方法:如何将参数传递给一个名为在的NSTimer

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

现在这个语法没有按” t似乎是正确的。我试着用NSInvocation的,但我得到了一些问题:

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

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

我应该如何使用调用?

回答

11

给出这样的定义:

- (void)timerFired:(NSTimer *)timer 
{ 
    ... 
} 

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

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

在您的计时器方法,你就可以通过计时器对象的userInfo方法来访问这个对象:

- (void)timerFired:(NSTimer *)timer 
{ 
    Game *game = [timer userInfo]; 
    ... 
} 
2

你可以通过NSDictionary命名对象(如myParamName => myObject)通过userInfo参数这样

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

然后在timer:方法:

- (void)timer:(NSTimer *)timer { 
    id myObject = timer.userInfo[@"myParamName"]; 
    ... 
} 
+0

如果您需要传递几个对象,那就是要走的路。但如果它只是一个单一的对象,你不需要将它封装到字典中。 – DarkDust 2011-03-02 10:45:15

+0

是的。我刚刚看到通知使用userInfo字典,所以认为保持一致性。 – Eimantas 2011-03-02 10:58:32

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

调用自身并不尽一切invocationWithMethodSignature,它只是创建一个对象,它是能够在正确的方式来填充。

相关问题