分享

NSTimer 使用 绝对超详细(2)

 睁开眼就变帅 2016-09-07


先说一下,初始化方法

+ scheduledTimerWithTimeInterval:invocation:repeats:
+ scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:

这两个是创建一个定时器,并加入到当前运行循环中,即我们可以这样去理解,这样初始化一个定时器时,在(NSTimeInterval)seconds 时间之后,自动启动定时器。


而以下两个初始化方法这不一样:

+ timerWithTimeInterval:invocation:repeats:
+ timerWithTimeInterval:target:selector:userInfo:repeats:


这两个同样是创建,但没有加入到,运行循环中。class method to create the timer object without scheduling it on a run loop.然后,建立之后,必须(after creating it, you must add the timer to a run loop manually by calling the addTimer:forMode: method of the corresponding NSRunLoop object.),这就是与上面两个方法的区别。

  //创建一个定时器
       _timer=[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(changeTimeAtTimedisplay) userInfo:nil repeats:YES];




_timer=[NSTimer timerWithTimeInterval:10 target:self selector:@selector(changeTimeAtTimedisplay) userInfo:nil repeats:YES];
       //必须手动加入到当前循环中去
       NSRunLoop *runloop=[NSRunLoop currentRunLoop];
       [runloop addTimer:_timer forMode:NSDefaultRunLoopMode];


以上两端代码效果是一样的



关于这个方法:

Firing a Timer
– fire


其实他并不是真的启动一个定时器,从之前的初始化方法中我们也可以看到,建立的时候,在适当的时间,定时器就会自动启动。那这个方法是干什么的呢。

You can use this method to fire a repeating timer without interrupting its regular firing schedule. If the timer is non-repeating, it is automatically invalidated after firing, even if its scheduled fire date has not arrived.

这是官方文档的说法,英文说的很清楚,但我们理解还不是很到位,为了彻底搞懂它的功能。我又做了一个测试。


也是很简单,把上面那个定时器,改变一点

//初始化的时候创建一个定时器

- (id) initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    
    if (self) {
        // Custom initialization
        
        //创建一个定时器,
        
       _timer=[NSTimer timerWithTimeInterval:10 target:self selector:@selector(changeTimeAtTimedisplay) userInfo:nil repeats:YES];
     

//手动加入到循环中

      NSRunLoop *runloop=[NSRunLoop currentRunLoop];

 [runloop addTimer:_timer forMode:NSDefaultRunLoopMode];


//当然这个定时器会自动启动,只不多过了十秒之后,才触发

}

return self

}



当我们单击“开始”按钮时,


- (IBAction)startTime:(id)sender {
  
    //只是简单地调用一下这个方法,看到底功能是什么
  [_timer fire];

}

结果是,单击一下按钮,倒计时减1,单击一下减1,即它把触发的时间给提前了,但过十秒后倒计时还会减1,即它只是提前触发定时器,而不影响之前的那个定时器设置的时间,就好比我们等不及要去看一场球赛,赶紧把车开快些一样,fire的功能就像让我们快些到球场,但却不影响球赛开始的时间。

还记得之前那个初始化定时器时,设置的是YES吗,当我们,改为NO时,即不让它循环触发时,我们此时再单击开始按钮。会猛然发现,倒计时减1了,但当我们再点击开始按钮时,会发现倒计时,不会动了。原因是:我们的定时器,被设置成只触发一次,再fire的时候,触发一次,该定时器,就被自动销毁了,以后再fire也不会触发了。


现在 我们再看官方的解释,或许就会更明白了,



You can use this method to fire a repeating timer without interrupting its regular firing schedule. If the timer is non-repeating, it is automatically invalidated after firing, even if its scheduled fire date has not arrived.

这就对了,fire并不是启动一个定时器,只是提前触发而已。











    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多