6

メソッドを呼び出すタイマーがありますが、このメソッドには 1 つのパラメーターが必要です。

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 に答える