您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS 中 NSTimer 的使用注意事項

編輯:iOS 相關資訊

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 加入某個 run loop;而 scheduled 的初始化方法則會以預設 mode 直接加入目前的 run loop。

範例:

[NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(startFindApartment:) userInfo:nil repeats:YES];

// 或
NSTimer *myTimer = [NSTimer timerWithTimeInterval:3.0 target:self selector:@selector(timerFired:) userInfo:nil repeats:NO];
[[NSRunLoop currentRunLoop] addTimer:myTimer forMode:NSDefaultRunLoopMode];

2、觸發(啟動)

定時器建立後(若非 scheduled 則加入 run loop 後),會在初始化時指定的 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;

這是唯一能將計時器從 run loop 移除的方法。

4、多執行緒中的使用

在主執行緒(main thread)中使用定時器時,兩種初始化方法都能用;若是在子執行緒中使用,則只能使用方法一 timerWithTimeInterval:...,並且啟動時不能用 fire,只能讓 run loop 持續執行下去:

_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]]);
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved