Passing parameters to the method called by a NSTimer

Viewed 40966

How can I pass a parameter to the method called by a NSTimer? My timer looks like this:

[NSTimer scheduledTimerWithTimeInterval:4 target:self selector:@selector(updateBusLocation) userInfo:nil repeats:YES];

and I want to be able to pass a string to the method updateBusLocation. Also, where am supposed to define the method updateBusLocation? In the same .m file that I create the timer?

EDIT:

Actually I am still having problems. I am getting the error message:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* -[MapKitDisplayViewController updateBusLocation]: unrecognized selector sent to instance 0x4623600'

Here is my code:

- (IBAction) showBus {

//do something

[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateBusLocation) userInfo:txtFieldData repeats:YES];
[txtFieldData release];
 }


 - (void) updateBusLocation:(NSTimer*)theTimer
 {
      NSLog(@"timer method was called");
      NSString *txtFieldData = [[NSString alloc] initWithString:(NSString*)[theTimer userInfo]];
if(txtFieldData == busNum.text) {
    //do something else
    }
    }

EDIT #2: Never mind your example code works fine thanks for the help.

6 Answers

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.

Not a direct answer to the question but since i ran into this while searching and i needed something different it may help someone. I wanted to call a funciton in a helper class, that i needed to pass in the UIViewController, rather than passing it with the userinfo which would not allow me to call the function manually elsewhere i created another function which the timer would call and called the function that i was interested in from there. A workaround that helped.

Timer.scheduledTimer(timeInterval: 4, target: self, selector: #selector(self.timerFired), userInfo: nil, repeats:true);

func timerFired() {

myFunction(controller: self)

}
Related