【问题标题】:how to pause and resume NSTimer in iphone如何在 iphone 中暂停和恢复 NSTimer
【发布时间】:2011-05-07 20:27:22
【问题描述】:

你好 我正在开发小游戏应用程序。 当用户转到另一个视图[说设置视图]时,我需要暂停计时器。 当用户返回该视图时,我需要恢复计时器。

谁能解决这个问题...

在此先感谢...

【问题讨论】:

    标签: iphone objective-c ios4 nstimer nstimeinterval


    【解决方案1】:

    NSTimer 不能让您暂停它。但是,通过一些简单的变量,您可以自己创建效果:

    NSTimer *timer;
    double timerInterval = 10.0;
    double timerElapsed = 0.0;
    NSDate *timerStarted;
    
    -(void) startTimer {
      timer = [NSTimer scheduledTimerWithTimeInterval:(timerInterval - timerElapsed) target:self selector:@selector(fired) userInfo:nil repeats:NO];
      timerStarted = [NSDate date];
    }
    
    -(void) fired {
      [timer invalidate];
      timer = nil;
      timerElapsed = 0.0;
      [self startTimer];
      // react to timer event here
    }
    
    -(void) pauseTimer {
      [timer invalidate];
      timer = nil;
      timerElapsed = [[NSDate date] timeIntervalSinceDate:timerStarted];
    }
    

    这对我来说效果很好。

    【讨论】:

      【解决方案2】:

      您不能暂停计时器。但是,当用户进入设置视图时,您可以保存计时器的fireDate 以及当前日期。在此之后,您使计时器无效并让用户做他/她的事情。 一旦他/她切换回游戏,您创建一个新的计时器对象并将触发日期设置为旧触发日期加上用户在菜单中的时间(oldTime + currentTime)。

      【讨论】:

      • 谢谢,但我是 iphone 新手。你能给我一些演示样本,以便我可以轻松地完成它。
      • @JustSid,你能提供这个示例代码吗?..我知道这是几年前的事了,但对我来说创建一个关于这个的新问题是多余的。 :)
      【解决方案3】:

      您可以使用此代码在 NSTimer 中实现暂停和恢复功能

      //=========new timer update method=============
      
      -(void) updateTimer {
      
          NSDate *currentDate = [NSDate date];
      
          NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:startDate];
          NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
      
      
          NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
          [dateFormatter setDateFormat:@"mm:ss.S"];
          [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
      
          NSString *timeString = [dateFormatter stringFromDate:timerDate];
          lblMessage.text = timeString;
          pauseTimeInterval = timeInterval;
      
         }
      
       -(IBAction) startBtnPressed:(id)sender
          {
      //=============================new update with start pause==================
      if(running == NO) {
          running = YES;
      
          startDate = [NSDate date] ;
          startDate = [[startDate dateByAddingTimeInterval:((-1)*(pauseTimeInterval))] retain];
          stopWatchTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/10.0 target:self selector:@selector(updateTimer) userInfo:nil repeats:YES];
      }
      else {
          running = NO;
          [stopWatchTimer invalidate];
          stopWatchTimer = nil;
          [self updateTimer];
      }
      }
      

      在.h文件中声明NSDate startDate;

      NSTimeInterval 暂停时间间隔; 并在 viewdidload pausetimeInterval=0.0;祝你好运

      【讨论】:

        【解决方案4】:

        您不能暂停 NSTimer。但是,您可以将其无效并在需要时创建一个新的。

        【讨论】:

        • 谢谢,但我不能无效,因为当我转到另一个视图并返回时,它应该从它停止的地方开始。
        【解决方案5】:
        on Start - 
        startNewCapture = [NSDate date];
        
        on Pause - 
        captureSessionPauseDate = [NSDate date]; 
        captureSessionTimeInterval = [captureSessionPauseDate timeIntervalSinceDate:startNewCapture];
        
        on Resume - 
        NSDate *dateNow = [NSDate date];
        startNewCapture = [NSDate dateWithTimeInterval:-captureSessionTimeInterval sinceDate:dateNow];
        

        【讨论】:

          【解决方案6】:
          - (IBAction)pauseResumeTimer:(id)sender {
          
              if (timerRunning == NO) {
                  timerRunning = YES;
          
              [pauseTimerBtn setTitle:@"Resume" forState:UIControlStateNormal];
              NSString *stringVal = [NSString stringWithFormat:@"%@",timeTxt.text];
              stringVal = [stringVal stringByReplacingOccurrencesOfString:@":" withString:@"."];
          
              float tempFloatVal = [stringVal floatValue];
              int minuteValue = floorf(tempFloatVal);
              float tempSecVal = [stringVal floatValue] - floorf(tempFloatVal);
              int secondVal = tempSecVal*100;
              minuteValue = minuteValue*60;
          
              oldTimeValue = minuteValue + secondVal;
              [timer invalidate];
              timer = nil;
          }
          else
          {
              timerRunning = NO;
              [pauseTimerBtn setTitle:@"Pause" forState:UIControlStateNormal];
              startDate = [NSDate date];
              timer = [NSTimer scheduledTimerWithTimeInterval:0.25 target:self selector:@selector(timer:) userInfo:nil repeats:YES];
              }    
          }
          
          - (void)runTimer:(NSTimer *)timer {
              NSInteger secondsAtStart = (NSInteger)[[NSDate date] timeIntervalSinceDate:startDate];
              secondsAtStart = secondsAtStart + oldTimeValue;
              NSInteger seconds = secondsAtStart % 60;
              NSInteger minutes = (secondsAtStart / 60) % 60;
              NSInteger hours = secondsAtStart / (60 * 60);
              NSString *result = nil;
              result = [NSString stringWithFormat:@"%02ld:%02ld",(long)minutes,(long)seconds];
              timeTxt.text   =  result;
          
          }
          

          【讨论】:

            【解决方案7】:

            你最终弄明白了吗?我看到你说当你进入另一个视图时你不能使你的计时器失效。你能解释一下你的意思吗? NSTimers 不能被暂停,模拟暂停它们的方法通常涉及使它们无效。然后,您可以通过创建一个新的计时器来模拟“取消暂停”,然后该计时器将再次启动。这将模拟暂停和取消暂停的计时器。

            对于那些想要一种可能更方便的方法的人,我编写了一个控制器类,可以方便地处理暂停和取消暂停计时器。你可以在这里找到它:https://github.com/LianaChu/LCPausableTimer

            您可以使用我编写的控制器类来创建新的定时器,然后您可以通过调用控制器类上的方法“pauseTimer”和“unpauseTimer”来暂停和取消暂停定时器。

            我非常感谢任何 cmets 或反馈,例如您如何使用它、您希望看到哪些更改或您希望我添加的任何功能。请不要犹豫,在这里回复您的 cmets,或在 Github 页面的问题选项卡上发布。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2017-01-08
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多