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];

[[NSRunLoopcurrentRunLoopaddTimer: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保持线程为活跃状态,定时器才能运行正常。


并且启动定时器不能用fire,只能让runloop一直执行下去,sample code:

_timer=[NSTimertimerWithTimeInterval:0.5target:selfselector:@selector(timeSchedule)userInfo:nilrepeats:YES];

   NSRunLoop *runLoop=[NSRunLoopcurrentRunLoop];

    [runLoopaddTimer:_timerforMode:NSDefaultRunLoopMode];

   while ([runLooprunMode:NSDefaultRunLoopModebeforeDate:[NSDate distantFuture]]);



0 0