Passing parameters to the method called by a NSTimer Passing parameters to the method called by a NSTimer objective-c objective-c

Passing parameters to the method called by a NSTimer


You need to define the method in the target. Since you set the target as 'self', then yes that same object needs to implement the method. But you could have set the target to anything else you wanted.

userInfo is a pointer that you can set to any object (or collection) you like and that will be passed to the target selector when the timer fires.

Hope that helps.

EDIT: ... Simple Example:

Set up the timer:

    NSTimer* timer = [NSTimer scheduledTimerWithTimeInterval:2.0                               target:self                               selector:@selector(handleTimer:)                               userInfo:@"someString" repeats:NO];

and implement the handler in the same class (assuming you're setting the target to 'self'):

- (void)handleTimer:(NSTimer*)theTimer {   NSLog (@"Got the string: %@", (NSString*)[theTimer userInfo]);}


You can pass your arguments with userInfo:[NSDictionary dictionaryWithObjectsAndKeys:parameterObj1, @"keyOfParameter1"];

A simple example:

[NSTimer scheduledTimerWithTimeInterval:3.0                                 target:self                               selector:@selector(handleTimer:)                               userInfo:@{@"parameter1": @9}                                repeats:NO];- (void)handleTimer:(NSTimer *)timer {    NSInteger parameter1 = [[[timer userInfo] objectForKey:@"parameter1"] integerValue];}


For Swift 4.0:

You can have a function with any parameters you want and use the "scheduledTimer" block to execute the code you need to repeat.

func someFunction(param1: Int, param2: String) {    let timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in        print(param1)        print(param2)    }}

Be careful to call timer.invalidate() when you finish to prevent it from running continuously.