开发者

Objective-C: NSTimer selector

Is it possible to initiate a timer and pass the selector method with multiple arguments?

Below is a simple example of a working timer:

gameTimer = [NSTimer scheduledTimerWithTimeInterval:0.5
                                             target:self
                                           selector:@selector(gameLoop:)
                                           userInfo:nil
                                            repeats:YES];

The selector method would be named - (void)gameLoop:(NSTimer *)theTimer;

Is it possible to pass this selector method with multiple arguments? So that the gameLoop method could also deal wi开发者_运维技巧th an int value and a bool value?

The following obviously doesn't work, but might highlight what I'm after:

gameTimer = [NSTimer scheduledTimerWithTimeInterval:0.5
                                             target:self
                                           selector:@selector(gameLoop:NO:75)
                                           userInfo:nil
                                            repeats:YES];

- (void)gameLoop:(NSTimer *)theTimer isRunning:(bool)running numberOfSteps:(int)steps;


I disagree with BOTH answers. Of course you can pass whatever info you want to the method your NSTimer calls. That's what the

userInfo 

parameter is for!

NSNumber *steps = [NSNumber numberWithInt: 75];   

NSDictionary *info = [NSDictionary dictionaryWithObject: steps forKey: @"steps"];
//Pass any objects in a dictionary for easy extraction.
gameTimer = [NSTimer scheduledTimerWithTimeInterval:0.5
                                         target:self
                                       selector:@selector(gameLoop:)
                                       userInfo: info
                                        repeats:YES];

Now you can extract the userInfo in the selector.

- (void)gameLoop:(NSTimer *)theTimer{
    NSDictionary info = [theTimer userInfo];
    NSInteger steps = [[info valueForKey: @"steps"] integerValue];
    //etc...
}


No.

From the documentation http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/nstimer_Class/Reference/NSTimer.html#//apple_ref/occ/clm/NSTimer/scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:

aSelector

The message to send to target when the timer fires. The selector must have the following signature:

- (void)timerFireMethod:(NSTimer*)theTimer

The timer passes itself as the argument to this method.

Could workaround with something like...

- (void)gameLoopA:(NSTimer *)theTimer {
    [self gameLoop:theTimer isRunning:NO numberOfSteps:75];
}

- (void)gameLoopB:(NSTimer *)theTimer {
    [self gameLoop:theTimer isRunning:NO numberOfSteps:50];
}

// etc, etc.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜