首页 / IOS / IOS 中NSTimer使用注意事项
IOS 中NSTimer使用注意事项
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了IOS 中NSTimer使用注意事项,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1810字,纯文字阅读大概需要3分钟。
内容图文
![IOS 中NSTimer使用注意事项](/upload/InfoBanner/zyjiaocheng/1168/c3602c547efe4b0690e67fbe49daaa6b.jpg)
1、初始化
+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo;
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo;
注意:userInfo是值NSTimer携带的用户信息。
不用scheduled方式初始化的,需要手动addTimer:forMode: 将timer添加到一个runloop中。
而scheduled的初始化方法将以默认mode直接添加到当前的runloop中.
sample:
[NSTimer scheduledTimerWithTimeInterval:2 target:selfselector:@selector(startFindApartment:) userInfo:nil repeats:YES];
或
NSTimer *myTimer = [NSTimertimerWithTimeInterval:3.0 target:selfselector:@selector(timerFired:) userInfo:nilrepeats:NO];
[[NSRunLoopcurrentRunLoop] addTimer:myTimerforMode:NSDefaultRunLoopMode];
2、触发(启动)
当定时器创建完(不用scheduled的,添加到runloop中后,该定时器将在初始化时指定的timeInterval秒后自动触发。
NSTimer *timer=[NSTimer timerWithTimeInterval:0.5target:selfselector:@selector(timeSchedule) userInfo:nilrepeats:YES];
NSRunLoop *runLoop=[NSRunLoopcurrentRunLoop];
[runLoop addTimer:timer forMode:NSDefaultRunLoopMode];
[timer fire];
可以使用-(void)fire;方法来立即触发该定时器;
3、停止
- (void)invalidate;
这个是唯一一个可以将计时器从runloop中移出的方法。
4、在多线程开发中,如果是在mainthread中使用定时器,两种初始化方法都能使用,如果是在子线程中使用定时器,只能使用方法:
+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo;
_timer =[NSTimertimerWithTimeInterval:0.5target:selfselector:@selector(timeSchedule) userInfo:nilrepeats:YES];
NSRunLoop *runLoop=[NSRunLoopcurrentRunLoop];
[runLoop addTimer:_timerforMode:NSDefaultRunLoopMode];
while ([runLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDatedistantFuture]]);
原文:http://blog.csdn.net/richard_rufeng/article/details/25961017
内容总结
以上是互联网集市为您收集整理的IOS 中NSTimer使用注意事项全部内容,希望文章能够帮你解决IOS 中NSTimer使用注意事项所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。