如何启动和停止NSTimer? [英] How Can I Start And Stop NSTimer?

查看:82
本文介绍了如何启动和停止NSTimer?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发秒表应用程序。
在我的应用程序中,有两个UIButtons, StartBtn StopBtn ,还使用 NSTimer



现在,我想在用户点击 StartBtn NSTimer $ c>并且当你点击 StopBtn 时停止。



我知道 NSTimer [MyTimerName invalidate]; 方法停止,但我不知道如何启动 NSTimer c> c> c> c> 使用;而不是将创建/销毁从开始/停止分离,它们都一起滚动。



因此,您需要使用存在 NSTimer 对象作为标志来指示它是否正在运行;类似这样:

  //私有方法
@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
重复:YES];
}
}

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

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


I develop Stop Watch Application. In my application, there are Two UIButtons , StartBtn and StopBtn, And also I use NSTimer.

Now, i want to start NSTimer when user click on StartBtn and also stop when your click on StopBtn.

I know that NSTimer is stopped by [MyTimerName invalidate]; method but I don't know how to start NSTimer again?

解决方案

The NSTimer class is a bit awkward to use; rather than separating the creation/destruction from the start/stop, it's all rolled together. In other words the timer starts as soon as it's created and stops as soon as it's destroyed.

You therefore need to use the existence of the NSTimer object as a flag to indicate if it's running; something like this:

// 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");
}

这篇关于如何启动和停止NSTimer?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆