2011-03-02 17 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,它只是創建一個對象,它是能夠在正確的方式來填充。

相關問題