how to stop a timer triggered runloop?

nico picture nico · Jul 19, 2010 · Viewed 14.3k times · Source

if i set up a runloop like that:

NSRunloop* loop = [NSRunloop currentRunLoop];
[runLoop addTimer:anyTimer forMode:NSDefaultRunLoopMode];

can i stop it again ? or is the only way to ignore the notification i use to trigger the further action ?

ok, i give an example for the problem:

-(void)blinkeffekt:(double)pollingTime{

NSRunLoop* runLoop = [NSRunLoop currentRunLoop];

if (pollingTime != 0) {
    NSTimeInterval interval =(double)pollingTime / 1000;
    NSTimer timer = [NSTimer scheduledTimerWithTimeInterval:interval target:self selector:@selector(polling) userInfo:nil repeats:YES];
    [runLoop addTimer:timer forMode:NSDefaultRunLoopMode];
}
else {

    [timer invalidate];
}

}

surely, here are several errors - no question. but i think, it shows my problem. and this is not really solvable with the answers until now.

i need to run a timer and stop it later. and ideally out of another function in the class. but then i cannot access "timer" anymore and runloop doesnt allow to figure out, if such a "message" is available. and it would be extremely ineffective, if i would register for each calling of the function a new timer.

Answer

willcodejavaforfood picture willcodejavaforfood · Jul 19, 2010

You need to send a invalidate message to the timer to remove it from the RunLoop.

See Doc

[anyTimer invalidate];