美文网首页
NSTimer简单用法

NSTimer简单用法

作者: coder_那一抹刚吹过的风 | 来源:发表于2016-06-29 20:22 被阅读39次

    开始前咱们先知道NSTimer是用来的干嘛的。

     A timer waits until a certain time interval has elapsed and then fires, 
    sending a specified message to a target object.
    

    从这里我们可以看出来,NSTimer就是我为了过一段时间想目标发送一个消息,从而执行一系列的操作。既然我们已经知道用法。所以咱们先来个最简单的用法

    [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(run:) userInfo:nil repeats:YES];
    

    方法实现里直接打印helloworld就好,这里我就不再占用篇幅去写了。自己去补就好。上面这个函数的意思就是每隔1.5秒执行一次run方法。注意:如果repeats参数为NO时,只会执行一遍该方法。
    接下来我们看看怎样控制定时器的开关

    [_timer setFireDate:[NSDate distantFuture]];
    

    调用上面语句,定时器就会关闭

    [_timer setFireDate:[NSDate distantPast]];
    

    上面就是开启定时器

    关于NSTimer也不能说的太深,因为牵涉到一些runloop的知识。大家有兴趣的可以去研究一下。我也做过这方面的研究,只可惜研究尚欠,难等大雅之堂,今天就不跟大家分享,等我研究的小有成就的时候。在跟大家分享。

    相关文章

      网友评论

          本文标题:NSTimer简单用法

          本文链接:https://www.haomeiwen.com/subject/deexjttx.html