Search code examples
iosobjective-cnstimer

How do I change timing for NSTimer?


I have the following code:

timer = [[NSTimer scheduledTimerWithTimeInterval:0.50 target:self selector:@selector(onTimer) userInfo:nil repeats:YES] retain];    

-(void) onTimer 
{
}

After every 0.50 seconds the OnTimer method is called.

But now I want to increment the time-interval.

That means:

OnTimer calls after 0.55
OnTimer calls after 0.60
OnTimer calls after 0.65
OnTimer calls after 0.70
OnTimer calls after 0.75
& so on.

Is there any solution for this?? I have tried lot but its not working.


Solution

  • Sure you can do this. Change repeats:YES to repeats:NO so that the timer doesn't repeat, and then in onTimer, just start a new timer with a longer interval. You need a variable to hold your interval so that you can make it a bit longer each time through onTimer. Also, you probably don't need to retain the timer anymore, as it will only fire once, and when it does, you'll get a new timer.

    I'm no Objective-C expert (or iOS expert...) and it's been a while but I think something like this:

    float gap = 0.50;
    
    [NSTimer scheduledTimerWithTimeInterval:gap target:self selector:@selector(onTimer) userInfo:nil repeats:NO];
    
    -(void) onTimer {
        gap = gap + .05;
        [NSTimer scheduledTimerWithTimeInterval:gap target:self selector:@selector(onTimer) userInfo:nil repeats:NO];
    }
    

    Something like that? Oh, and I'm really not too sure about the retain semantics here... read the docs to make sure you don't leak!