定时器学习与使用

作者: 石丘 | 来源:发表于2015-12-02 19:55 被阅读4060次

API介绍


+(NSTimer *)scheduledTimerWithTimeInterval:ti invocation:invocation repeats:yesOrNo;
+(NSTimer *)scheduledTimerWithTimeInterval:ti target:(id)aTarget selector:aSelector userInfo:userInfo repeats:yesOrNo;```
scheduled开头的两个方法是比较常用的创建定时器的方法 因为这两个初始化定时器后直接加入到当前运行循环中 在TimeInterval后 自动启动 比较方便 
`+(NSTimer *)timerWithTimeInterval:ti invocation:invocation repeats:yesOrNo;`
`+(NSTimer *)timerWithTimeInterval:ti target:aTarget selector:aSelector userInfo:userInfo repeats:yesOrNo;`
这两个同样是创建 但没有加入到runloop中 建立之后 必须手动加入,见例2
关于为什么会出现比较麻烦这种方式 可能是因为简单那种方式不能在子线程调用?
`-(instancetype)initWithFireDate:date interval:ti target:t selector:s userInfo:ui repeats:rep NS_DESIGNATED_INITIALIZER;`
关于以上几个生成方法的参数
1:ti 多久后执行 如果是0 系统就0.1毫秒后执行 
2:aTarget调用后面 方法的对象 执行后有强指针指向 直到调用invalidate
3:aSelector你要定时执行的方法
4:userInfo 可以捎带可对象 invalidate前不会被释放
5:repeats yesOrNo  YES重复执行 NO只执行一次

`-(void)fire;`
无视延时直接触发
`@property (copy) NSDate *fireDate;`
设置定时器开始运行的时间
`@property (readonly) NSTimeInterval timeInterval;`
定时器延时时间`typedef double NSTimeInterval`这货是个double
`@property NSTimeInterval tolerance NS_AVAILABLE(10_9, 7_0);`

`-(void)invalidate;` 
停止接收 并从Runloop中请求删除 
`@property (readonly, getter=isValid) BOOL valid;`
是否在运行
`@property (nullable, readonly, retain) id userInfo;`
其他信息
`@end`

####一些小示例
***
示例1:直接用scheduled生成
`[NSTimer scheduledTimerWithTimeInterval:2.0f target:self selector:@selector(scanTimeout:) userInfo:nil repeats:NO];`
示例2:需手动加入RunLoop
`self.timer =[NSTimer timerWithTimeInterval:5.0 target:self selector:@selector(scanError) userInfo:nil repeats:YES];`
`NSRunLoop *runLoop = [NSRunLoop currentRunLoop];`
`[runLoop addTimer:self.timer forMode:NSDefaultRunLoopMode];`

如果是在子线程调用 需调用` [runloop run];`

实现定时器停止、运行可使用下面方法:
`[timer setFireDate:[NSDate distantFuture]];//停止`
`[timer setFireDate:[NSDate distantPast]];//运行`
 
 移除定时器invalidate这步是必须的上面参数有提到 不然不会释放 
`[timer invalidate];`
`timer = nil;//这里很多地方提到一定置为nil 我没搞也释放了 建议还是加上保险`

 [小练习](https://github.com/julysiji/1547-NStimer)
[一篇比较详细的介绍](http://www.cnblogs.com/smileEvday/archive/2012/12/21/NSTimer.html)

相关文章

  • 定时器学习与使用

    API介绍

  • 13. Jmeter-定时器

    Jmeter-定时器介绍与使用 固定定时器 Uniform Random Timer Precise Throug...

  • iOS 计时器

    GCD定时器 Dispatch Source Timer 是一种与 Dispatch Queue 结合使用的定时器...

  • IOS开发 定时器和视图移动

    本字学习内容: 1.定时器对象的概念 2.定时器对象的创建 3.使用定时器移动视图 【ViewController...

  • IOS开发 定时器和视图移动

    本字学习内容: 1.定时器对象的概念 2.定时器对象的创建 3.使用定时器移动视图 【ViewController...

  • 无标题文章

    iOS NSTimer使用详解-开启、关闭、移除 定时器定时器详解ios定时器关闭定时器NSTimer 1、要使用...

  • 状态和生命周期

    学习使用Clock组件,来重用和封装。并设置定时器。封装了一个定时器,如: Try it on CodePen. ...

  • Python定时任务APScheduler使用

    Python定时器筛选 对比了Python常用定时器库,scheduler功能更齐全,使用简单,学习成本低 APS...

  • VUE中定时器如何使用?

    定时器的创建和使用 定时器的销毁 定时器 setTimeout()方法 和 setInterval() 使用方法相...

  • 2017-12-21

    今天我们学习了定时器,定时器人类最早使用的定时工具是沙漏或水漏,但在钟表诞生发展成熟之后,人们开始尝试使用这种全新...

网友评论

本文标题:定时器学习与使用

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