How to pass an argument to a method called in NSTimer

I have a timer that calls a method, but this method takes one parameter:

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

it should be

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

now this syntax does not seem to be correct. I tried with NSInvocation, but I am having problems:

 timerInvocation = [NSInvocation invocationWithMethodSignature: [self methodSignatureForSelector:@selector(timer:game)]]; theTimer = [NSTimer scheduledTimerWithTimeInterval:animationInterval invocation:timerInvocation repeats:YES]; 

How do I use Invocation?

+6
objective-c arguments nstimer nsinvocation
source share
3 answers

Given this definition:

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

Then you need to use @selector(timerFired:) (method name without any spaces or argument names, but including colons). The object you want to transfer ( game ?) userInfo: through the userInfo: part:

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

In your timer method, you can access this object using the method of the userInfo object of the timer object:

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

As @DarkDust points out, NSTimer expects its target method to have a specific signature. If for some reason you cannot reconcile this, instead you can use NSInvocation as you suggest, but in this case you need to fully initialize it with a selector, a target, and arguments. For instance:

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

The invocationWithMethodSignature call alone does not do all this, it just creates an object that can be properly populated.

+5
source share

You can pass an NSDictionary with named objects (e.g. myParamName => myObject ) through a userInfo parameter like this

 theTimer = [NSTimer scheduledTimerWithTimeInterval:animationInterval target:self selector:@selector(timer:) userInfo:@{@"myParamName" : myObject} repeats:YES]; 

Then in the timer: method::

 - (void)timer:(NSTimer *)timer { id myObject = timer.userInfo[@"myParamName"]; ... } 
+2
source share

All Articles