ChrisP
ChrisP

Reputation: 10116

How do I pass an argument to @selector()?

I have the following NSTimer call

[NSTimer scheduledTimerWithTimeInterval:2.0
                               target:self
                             selector:@selector(panelVisibility:)
                             userInfo:nil
                              repeats:NO];

-(void)panelVisibility:(BOOL)visible{
...
}

where I need to pass a BOOL value to the panelVisibility method. How do I specify the parameter value?

Upvotes: 1

Views: 2876

Answers (2)

sidyll
sidyll

Reputation: 59277

You can't do that. Note that the docs says the method must have the following signature:

- (void)timerFireMethod:(NSTimer*)theTimer

Use the userInfo parameter to pass an [NSNumber nnumberWithBool:bool] and retrieve it by calling:

BOOL isSomething = [[theTimer userInfo] boolValue];

Inside the method the timer called when fired.

Upvotes: 1

aroth
aroth

Reputation: 54796

In this instance, you don't. Check the reference docs:

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.

So the only parameter your panelVisibility: method can accept is an NSTimer*, and the timer will pass this in automatically for you.

What you can do, however, is use the userInfo field to pass whatever other information you want. So you could, for instance, do:

[NSTimer scheduledTimerWithTimeInterval:2.0
                               target:self
                               selector:@selector(panelVisibility:)
                               userInfo:[NSNumber numberWithBool: myBool]
                               repeats:NO];

...and then have:

-(void)panelVisibility:(NSTimer*)theTimer{
    BOOL visible = [theTimer.userInfo boolValue];
    //...
}

Upvotes: 8

Related Questions