无法停止重复计时器

时间:2014-07-03 15:23:53

标签: ios nstimer

所以我正在使用重复NSTimer来跟踪视频播放器的进度。当它达到一定时间时,视频应该停止/暂停,并且计时器当然也应该是无效的。这是我计划用来阻止它的代码:

- (void)stopPlayer{
    if (self.playerIsPlaying) {
        [self.player pause];
        self.playerIsPlaying = NO;
        self.inPause = NO;
        [self.timer invalidate]; //This is NOT the repeating timer
        self.timer = nil;
        NSLog(@"Invalidating tracker, timeInterval %f",self.tracker.timeInterval);
        [self.tracker invalidate]; //THIS IS THE REPEATING TIMER
        self.tracker = nil;
    }
    [UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        self.restartArea.alpha = 1;
    } completion:^(BOOL finished) {
        self.atEndOfVideo = YES;
    }];
}

但由于某些原因视频暂停,计时器仍在继续。日志语句Invalidating tracker, timerInterval...确实显示哪条线路运行并且计时器也设置为nil,但为什么它仍在运行?

我在想这是因为我在self对象设置为unsafe_retained引用的块中安排了此计时器。可能是这种情况吗?

这是负责触发计时器的块:

__unsafe_unretained typeof(self) weakSelf = self;
[self.slider setProgress:0 animated:YES completion:^{
    [weakSelf.player play];
    weakSelf.timer = [[NSTimer alloc]init];
    weakSelf.timer = [NSTimer scheduledTimerWithTimeInterval:weakSelf.clipLength target:weakSelf selector:@selector(stopPlayer) userInfo:nil repeats:NO];
    weakSelf.playerIsPlaying = YES;
    [weakSelf fireTimer]; //Here's the line that fires my repeating `tracker` timer.
    return;
}];

- (void)fireTimer{
    NSLog(@"0.1s timer fired");
    self.tracker = [[NSTimer alloc]init];
    self.tracker = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(trackProgress) userInfo:nil repeats:YES];
}

2 个答案:

答案 0 :(得分:0)

您是否尝试在主线程上创建计时器?

- (void)fireTimer{
    NSLog(@"0.1s timer fired");

    dispatch_async(dispatch_get_main_queue(), ^{
        self.tracker = [[NSTimer alloc]init];
        self.tracker = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(trackProgress) userInfo:nil repeats:YES];
    }];

}

答案 1 :(得分:0)

找到问题的答案! 原来,同一个计时器被解雇两次(为什么我只调用一次) 但无论如何,我添加了一条线,阻止它重新射击。

if(self.tracker){
    NSLog(@"Timer already fired");
}
else{
    self.tracker = [[NSTimer alloc]init];
    self.tracker = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(trackProgress) userInfo:nil repeats:YES];
}