IOS 中NSTimer使用註意事項 – iPhone手機開發技術文章 iPhone軟體開發教學課程

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.5
target:self
selector:@selector(timeSchedule)
userInfo:nil
repeats:YES];

NSRunLoop *runLoop=[NSRunLoop
currentRunLoop];

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

並且啟動定時器不能用fire,隻能讓runloop一直執行下去,sample code:

_timer=[NSTimer
timerWithTimeInterval:0.5
target:self
selector:@selector(timeSchedule)
userInfo:nil
repeats:YES];

NSRunLoop *runLoop=[NSRunLoop
currentRunLoop];

[runLoop addTimer:_timer
forMode:NSDefaultRunLoopMode];

while ([runLoop
runMode:NSDefaultRunLoopMode
beforeDate:[NSDate distantFuture]]);

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *