Reputation: 11
Is it possible to give an argument in a method when setting a NSTimer? I want to create something like the following:
[NSTimer [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(moveParticle:imageView) userInfo:nil repeats:YES];
Where "imageView" is the argument of the method. It gives me a error saying the it's expecting a semi-colon right after the parathesis after "imageView".
Any help?
Upvotes: 1
Views: 305
Reputation: 1318
See duplicate thread :
You'll need to used +[NSTimer scheduledTimerWithTimeInterval:invocation:repeats:]
instead. By default, the selector used to fire a timer takes one parameter. If you need something other than that, you have to create an NSInvocation object, which the timer will use instead.
An example :
NSMethodSignature * mSig = [NSMutableArray instanceMethodSignatureForSelector:@selector(moveParticle:)];
NSInvocation * myInvocation = [NSInvocation invocationWithMethodSignature:mSig];
[myInvocation setTarget:myArray];
[myInvocation setSelector:@selector(moveParticle:)];
[myInvocation setArgument:&imageView atIndex:2]; // Index 2 because first two arguments are hidden arguments (self and _cmd). The argument has to be a pointer, so don't forget the ampersand!
NSTimer *myTimer = [NSTimer scheduledTimerWithTimeInterval:0.05 invocation:myInvocation repeats:true];
Upvotes: 0
Reputation: 34243
That's what the userInfo parameter is for. You can pass your imageView as userInfo and cast it to the desired type (NSView?) in the method you provide as selector. e.g.:
- (void)moveParticle:(NSTimer*)theTimer
{
NSView* imageView = (NSView*)[theTimer userInfo);
...
}
Another approach (probably more useful here - as your target is self), would be to make the imageView an iVar and access that within moveParticle.
Upvotes: 1
Reputation: 9544
You want to use the userInfo to send arguments. Look at the documentation on how to use it. You will just make your function take a single NSTimer argument then the timer will return itself and you can read its userInfo dictionary.
Upvotes: 3