How can I programmatically pause an NSTimer?

前端 未结 15 1719
梦毁少年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:28

    I was also in need of pausable NSTimer. After reading this thread and your answers and realizing that only thing I need is to set timer's fireDate to distant future and then back to Now I made category to NSTimer with Pause and Resume methods. So I can simply pause timer by calling [myTimer pause]; and resume by calling [myTimer resume]; methods. Here it is, hope that it will help someone.

    Interface:

    #import 
    
    @interface NSTimer (Pausable)
    
    -(void)pause;
    -(void)resume;
    
    @end
    

    Implementation:

    #import "NSTimer+Pausable.h"
    
    @implementation NSTimer (Pausable)
    
    -(void)pause
    {
        [self setFireDate:[NSDate dateWithTimeIntervalSinceNow:[NSDate distantFuture]]]; //set fireDate to far future
    }
    
    -(void)resume
    {
        [self setFireDate:[NSDate date]];
    }
    
    @end
    

提交回复
热议问题