如何启动和停止NSTimer?

用户名

我开发秒表应用程序。在我的应用程序中,有两个UIButtonStartBtnStopBtn,我也使用NSTimer

现在,我想NSTimer在用户单击时开始StartBtn并且在您单击时也停止StopBtn

我知道该方法NSTimer已停止,[MyTimerName invalidate];但我不知道如何重新开始NSTimer

Trojanfoe

NSTimer班是一个有点尴尬的使用; 而不是将创建/破坏与开始/停止分离开来,而是将它们全部组合在一起。换句话说,计时器在创建后立即启动,在销毁后立即停止。

因此,您需要使用存在的的NSTimer对象作为标志,以表明它是否运行; 像这样的东西:

// Private Methods
@interface MyClass ()
{
    NSTimer *_timer;
}
- (void)_timerFired:(NSTimer *)timer;
@end

@implementation MyClass

- (IBAction)startTimer:(id)sender {
    if (!_timer) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:1.0f
                                                  target:self
                                                selector:@selector(_timerFired:)
                                                userInfo:nil
                                                 repeats:YES];
    }
}

- (IBAction)stopTimer:(id)sender {
    if ([_timer isValid]) {
        [_timer invalidate];
    }
    _timer = nil;
}

- (void)_timerFired:(NSTimer *)timer {
    NSLog(@"ping");
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章