這個範例示範兩件事:如何用 NSTimer 建立週期性計時器,以及如何讓 UIProgressView 隨時間逐步推進。直接看註解最清楚。
- (IBAction)startToMove:(id)sender {
// 切換旋轉動畫:若正在轉就停止,否則啟動
// stopAnimating 用於停止動畫效果
if ([self.myActivityIndicatorView isAnimating]) {
[self.myActivityIndicatorView stopAnimating];
} else {
[self.myActivityIndicatorView startAnimating];
}
}
- (IBAction)downloadProgress:(id)sender {
// 計時器:在固定的時間間隔後向指定物件發送訊息
// target 訊息要送給哪個物件
// timeInterval 間隔秒數
// selector 要呼叫的方法
// userInfo 附帶參數,此處不需要故傳 nil
// repeats 是否重複觸發
myTimer = [NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(download)
userInfo:nil
repeats:YES];
}
- (void)download {
self.myProgressView.progress += 0.1; // 每次推進的步長
if (self.myProgressView.progress == 1.0) {
// 進度條已滿,先讓計時器失效,否則會持續觸發
[myTimer invalidate];
myTimer = nil;
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"download completed!"
message:@"Hey!Lucy!"
delegate:nil
cancelButtonTitle:@"OK!"
otherButtonTitles:nil];
[alert show];
}
}scheduledTimerWithTimeInterval: 建立出來的計時器會被加入目前的 RunLoop,因此必須在有效的事件迴圈中才會觸發;如果在沒有 RunLoop 的執行緒(例如自己開的純背景執行緒)建立,計時器是不會動的。
另外,NSTimer 會對 target 產生強引用。也就是說只要計時器還沒 invalidate,它會一直握著 self,造成物件無法釋放。養成習慣:在 dealloc 或離開該情境時明確呼叫 invalidate。
最後,用浮點累加來比對 == 1.0 並不是最穩健的寫法,實務上改成 >= 1.0 更安全,能避免精度誤差導致進度條永遠停不或者使用時機。