NSTimer 的作用是以固定的時間間隔向目標物件發送特定訊息。最常見的用途之一,就是驅動進度條的更新。
建立計時器:
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti
invocation:(NSInvocation *)invocation
repeats:(BOOL)yesOrNo;
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti
target:(id)aTarget
selector:(SEL)aSelector
userInfo:(id)userInfo
repeats:(BOOL)yesOrNo;
啟動與停止:
- (void)fire; // 啟動
- (void)invalidate; // 停止
設定與查詢:
- (BOOL)isValid;
- (NSDate *)fireDate;
- (void)setFireDate:(NSDate *)date;
- (NSTimeInterval)timeInterval;
- (id)userInfo;
#import "AppDelegate.h"
// 最大下載時間
#define DOWNLOAD_TIMEOUT 60.0
static int sec = 0;
@interface AppDelegate () {
NSTimer *_timer;
}
@end
@implementation AppDelegate
- (void)dealloc {
[_window release];
[super dealloc];
}
- (void)initView {
// 建立進度條
UIProgressView *progress = [[UIProgressView alloc]
initWithFrame:CGRectMake(20, 60, 220, 30)];
[progress setBackgroundColor:[UIColor brownColor]];
[progress setProgressViewStyle:UIProgressViewStyleBar];
[progress setProgress:0];
[progress setTag:0x123];
[self.window addSubview:progress];
}
- (void)updateView {
sec++;
UIProgressView *pro = (UIProgressView *)[self.window viewWithTag:0x123];
if (pro) {
[pro setProgress:sec / DOWNLOAD_TIMEOUT animated:YES];
}
if (sec > DOWNLOAD_TIMEOUT) {
// 停止計時器的唯一方式:從 RunLoop 中移除
[_timer invalidate];
_timer = nil;
}
}
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
[self initView];
// 在當前 RunLoop 中加入計時器,每 0.5 秒呼叫 updateView 一次
_timer = [NSTimer scheduledTimerWithTimeInterval:0.5
target:self
selector:@selector(updateView)
userInfo:nil
repeats:YES];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
@end
幾個實務上很關鍵的觀念。
第一,invalidate 是唯一的停止方式。直接將 timer 設為 nil 並不會讓它停下,計時器仍被 RunLoop 持有並持續觸發,這是最常見的洩漏與「畫面莫名繼續跳動」的原因。
第二,scheduledTimerWithTimeInterval: 系列會把 timer 加入「當前的」RunLoop,且預設只在 default mode 中觸發。這代表使用者在 scrollView 上拖動(進入 tracking mode)時,timer 會停止更新。若需要滑動途中仍持續更新,得改用 NSRunLoopCommonModes 自行加入。
第三,timer 會強引用 target。若 target 又持有 timer,就形成循環引用,永遠無法釋放。實務上多半改用 GCD 的 dispatch_source_t 或 iOS 10 之後的 CADisplayLink/DispatchSourceTimer 來避開這個問題。
第四,這個範例以「每秒累加計數」模擬下載,真實場景中應該由實際的位元組數除以總大小來計算進度,計時器只負責定期重繪,避免每收到一個 chunk 就更新一次 UI 而拖慢主線程。