1

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?

codedev
  • 11
  • 1
  • possible duplicate of [Arguments in @selector](http://stackoverflow.com/questions/1349740/arguments-in-selector) or possibly http://stackoverflow.com/questions/6631879/how-do-i-pass-an-argument-to-selector – jscs Dec 03 '11 at 20:18
  • possible duplicate of [How to pass arguments when calling function with timer in objective c](http://stackoverflow.com/questions/1527175/how-to-pass-arguments-when-calling-function-with-timer-in-objective-c) – Brad Larson Dec 09 '11 at 20:33

3 Answers3

3

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.

Dancreek
  • 9,524
  • 1
  • 31
  • 34
1

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.

Thomas Zoechling
  • 34,177
  • 3
  • 81
  • 112
  • The thing is that there will be a random amount of stars on the screen . Maybe a NSMutableArray with the names of the image views? – codedev Dec 03 '11 at 16:57
0

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];
Community
  • 1
  • 1
Fatso
  • 1,278
  • 16
  • 46