How can I programmatically pause an NSTimer?

前端 未结 15 1630
梦毁少年i
梦毁少年i 2020-11-27 13:06

I\'m using an NSTimer to do some rendering in an OpenGL based iPhone app. I have a modal dialog box that pops up and requests user input. While the user is providing input

相关标签:
15条回答
  • 2020-11-27 13:13

    From here:

    http://discussions.apple.com/thread.jspa?threadID=1811475&tstart=75

    "You can store the amount of time that has passed since the timer started... When the timer starts store the date in an NSDate variable. Then when the user switches... use the method timeIntervalSinceNow in the NSDate class to store how much time has passed... note that this will give a negative value for timeIntervalSinceNow. When the user returns use that value to set an appropriate timer.

    I don't think there's a way to pause and restart a timer. I faced a similar situation. "

    0 讨论(0)
  • 2020-11-27 13:13

    Well, I find this as the best method to implement the pausing a timer thing. Use a static variable to toggle pause and resume. In pause, invalidate the timer and set it to nil and in the resume section reset the timer using the original code by which it was started.

    The following code works on the response to a pause button click.

    -(IBAction)Pause:(id)sender
    {
        static BOOL *PauseToggle;
        if(!PauseToggle)
        {
            [timer invalidate];
            timer = nil;
            PauseToggle = (BOOL *) YES;
        }
        else
        {
            timer = [NSTimer scheduledTimerWithTimeInterval:0.04 target:self selector:@selector(HeliMove) userInfo:nil repeats:YES];
            PauseToggle = (BOOL *) NO;
        }
    }
    
    0 讨论(0)
  • 2020-11-27 13:13

    Here is a Simple swift pause/play timer.

    https://github.com/AnthonyUccello/Swift-Pausable-Timer/blob/master/Timer.swift

    0 讨论(0)
  • 2020-11-27 13:15

    In my case, I had a variable 'seconds', and another 'timerIsEnabled'. When I wanted to pause the timer, just made the timerIsEnabled as false. Since the seconds variable was only incremented if timerIsEnabled was true, I fixed my problem. Hope this helps.

    0 讨论(0)
  • 2020-11-27 13:16

    The easiest way I managed to do it was like this:

    -(void) timerToggle{
        if (theTimer == nil) {
            float theInterval = 1.0/30.0;
            theTimer = [NSTimer scheduledTimerWithTimeInterval:theInterval target:self selector:@selector(animateBall:) userInfo:nil repeats:YES];
        } else {
            [theTimer invalidate];
            theTimer = nil;
        }
    }
    
    0 讨论(0)
  • 2020-11-27 13:20

    Old question, but I just wrote a lightweight utility class to accomplish exactly what OP is looking for.

    https://github.com/codeslaw/CSPausibleTimer

    Supports repeating timers as well. Hope it comes in handy!

    0 讨论(0)
提交回复
热议问题