Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
458 views
in Technique[技术] by (71.8m points)

objective c - How to pass an argument to a method called in a NSTimer

I have a timer calling a method but this method takes one paramether:

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

should be

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

now this syntax doesn't seems to be right. I tried with NSInvocation but I got some problems:

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

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

How should I use Invocation?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Given this definition:

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

You then need to use @selector(timerFired:) (that's the method name without any spaces or argument names, but including the colons). The object you want to pass (game ?) is passed via the userInfo: part:

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

In your timer method, you can then access this object via the timer object's userInfo method:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...