天天看點

IOS 中NSTimer使用注意事項

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

    [runLoop addTimer:_timerforMode:NSDefaultRunLoopMode];

    while ([runLooprunMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]);

繼續閱讀