IOS 中NSTimer使用注意事项
来源:互联网 发布:北京金山软件 编辑:程序博客网 时间:2024/05/16 23:37
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=[NSTimertimerWithTimeInterval:0.5target:selfselector:@selector(timeSchedule)userInfo:nilrepeats:YES];
NSRunLoop *runLoop=[NSRunLoopcurrentRunLoop];
[runLoopaddTimer:timerforMode: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;
一个run loop就是一个事件处理循环,用来不停的调配工作以及处理输入事件。使用run loop的目的是使你的线程在有工作的时候工作,没有的时候休眠。NSRunloop可以保持一个线程一直为活跃状态,不会马上销毁。
在多线程中使用定时器必须开启Runloop,因为只有开启Runloop保持线程为活跃状态,定时器才能运行正常。
_timer=[NSTimertimerWithTimeInterval:0.5target:selfselector:@selector(timeSchedule)userInfo:nilrepeats:YES];
NSRunLoop *runLoop=[NSRunLoopcurrentRunLoop];
[runLoopaddTimer:_timerforMode:NSDefaultRunLoopMode];
while ([runLooprunMode:NSDefaultRunLoopModebeforeDate:[NSDate distantFuture]]);
- IOS 中NSTimer使用注意事项
- iOS NSTimer使用注意事项
- iOS中定时器NSTimer使用
- IOS中关于NSTimer使用
- IOS中关于NSTimer使用
- iOS中定时器NSTimer使用
- iOS中NSTimer的使用
- iOS中定时器NSTimer使用
- iOS中定时器NSTimer使用
- iOS中定时器NSTimer使用
- NSTimer使用注意事项
- NSTimer使用注意事项
- iOS --- 使用NSTimer设置定时任务的注意事项
- iOS中定时器NSTimer的使用
- iOS中定时器NSTimer的使用
- iOS中定时器NSTimer的使用
- iOS中定时器NSTimer的使用
- IOS中关于NSTimer使用知多少
- 对于互联网金融大战,第三方基金销售也成了参与者 数米、好买接连参战
- Eclipse关联JDK源码
- 关于 MongoDB 你需要知道的几件事
- 序列化和反序列化
- 树的基本实现
- IOS 中NSTimer使用注意事项
- map的基本用法
- CI的session用法
- web config配置详解
- python核心编程 练习题 石头剪刀布
- apache phoenix的JAVA客户端访问
- oracle表连接
- OpenCV卷积核
- Solr开发文档