【问题标题】:how to clear NSTimer memory?如何清除 NSTimer 内存?
【发布时间】:2016-02-18 07:30:42
【问题描述】:

我正在使用NSTimer 在录制时在标签上显示秒数。 我在点击录制按钮时启动计时器,并在点击停止按钮时停止它。 当我点击播放按钮时,计时器没有重新启动。

-(void)startTimer
{
 playTimer = [NSTimer scheduledTimerWithTimeInterval:1
                                             target:self
                                           selector:@selector(timerController)
                                           userInfo:nil
                                            repeats:YES];
}
- (NSString*)getTimeStr : (int) secondsElapsed
{
seconds = secondsElapsed % 60;
int minutes = secondsElapsed / 60;
int hours = secondsElapsed/3600;
return [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds];
}

- (void)timerController{
seconds++;
[[self timeLabel] setText:[self getTimeStr:(seconds)]];
}

- (IBAction)recordTapped:(id)sender {
[self startTimer];
}

- (IBAction)stopTapped:(id)sender {
 [playTimer invalidate];
  playTimer=nil;
 _timeLabel.text=@"00:00:00";
}

- (IBAction)playTapped:(id)sender {
[self startTimer];
}

【问题讨论】:

  • 要重新启动计时器,您应该在startTimer函数的开头将seconds变量重置为0
  • 感谢您的完美工作。
  • 只是我注意到我的计时器只运行了 1 分钟。之后它又从 00:00:01 开始。你能帮我解决这个问题吗
  • 我忽略了另一个错误。您在getTimeStr: 函数中重用了变量seconds,这使得seconds 变量始终小于或等于59。将seconds 替换为int sec,当然,更改最后一行中的变量函数的sec 以及
  • 好的,我在一个小错误中失败了。现在工作正常

标签: ios objective-c nstimer


【解决方案1】:

正如 cmets 中提到的,周围有两个错误:

错误 #1

在重新启动计时器之前,您应该始终将变量 seconds 重置为 0(可能在 startTimer 的第一行重置它)

错误 #2

变量secondsgetTimeStr 函数的第一行覆盖。您应该将seconds 替换为int sec,对于return 行,将seconds 替换为sec

【讨论】:

    【解决方案2】:
    - (void)resetTimer {
        if(playTimer) {
            [playTimer invalidate];
            playTimer = nil;
        }
    }
    

    你应该在每次startTimer之前调用resetTimer方法。

    【讨论】:

      猜你喜欢
      • 2011-05-10
      • 1970-01-01
      • 2014-12-08
      • 1970-01-01
      • 2021-10-05
      • 2012-01-27
      • 2017-03-11
      • 2019-08-24
      • 2019-05-08
      相关资源
      最近更新 更多