achiral
achiral

Reputation: 601

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

Upvotes: 0

Views: 3314

Answers (2)

samfu_1
samfu_1

Reputation: 1160

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...
}

Upvotes: 12

nloko
nloko

Reputation: 696

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.

Upvotes: 0

Related Questions