在 iOS 7 之前,系統並未提供統一的進度回報機制,想追蹤一個耗時任務的完成狀況,往往得自己攤平各種計時器與計數器。iOS 7 之後推出的 NSProgress 正是為了解決這個問題:它標準化了進度的表達方式,同時支援父子節點的樹狀結構,讓多層任務的彙總變得自然。
用一個計時器模擬耗時工作,再對 fractionCompleted 做 KVO 觀察即可:
@interface ViewController () {
NSProgress *progress;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// totalUnitCount 代表整件事的「總工作單元數」
progress = [NSProgress progressWithTotalUnitCount:10];
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:@selector(task)
userInfo:nil
repeats:YES];
// 監聽完成比例
[progress addObserver:self
forKeyPath:@"fractionCompleted"
options:NSKeyValueObservingOptionNew
context:nil];
}
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context {
NSLog(@"進度 = %f", progress.fractionCompleted);
}
-(void)task {
// 每完成一個單元就累加
if (progress.completedUnitCount < progress.totalUnitCount) {
progress.completedUnitCount += 1;
}
}
@end
fractionCompleted 是 0 到 1 之間的比例值。若需要直接拿去顯示,NSProgress 另外提供了兩個預先格式化好的字串:
// 例如「10% completed」 @property (null_resettable, copy) NSString *localizedDescription; // 例如「1 of 10」 @property (null_resettable, copy) NSString *localizedAdditionalDescription;
現實中的任務往往還能再拆成子任務。NSProgress 以樹狀設計,透過「當前進度物件」的概念把子任務自動掛到父節點下:
- (void)viewDidLoad {
[super viewDidLoad];
progress = [NSProgress progressWithTotalUnitCount:10];
[progress addObserver:self
forKeyPath:@"fractionCompleted"
options:NSKeyValueObservingOptionNew
context:nil];
// 宣告接下來要分出去 5 個單元
[progress becomeCurrentWithPendingUnitCount:5];
[self subTaskOne];
[progress resignCurrent];
// 再分出另外 5 個單元
[progress becomeCurrentWithPendingUnitCount:5];
[self subTaskOne];
[progress resignCurrent];
}
-(void)subTaskOne {
// 子任務自身有 10 個單元
NSProgress *sub = [NSProgress progressWithTotalUnitCount:10];
for (int i = 0; i < 10; i++) {
sub.completedUnitCount++;
}
}
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context {
NSLog(@"= %@", progress.localizedAdditionalDescription);
}
這裡的關鍵在於:becomeCurrentWithPendingUnitCount: 會把該物件註冊為「當前執行緒的根進度節點」,resignCurrent 則取消註冊,兩者必須成對出現。當有物件被註冊為根節點後,後續以 progressWithTotalUnitCount: 建立的物件都會自動成為它的子節點。這種隱含的上下文關係可讀性偏差,也容易造成配對失誤。
Apple 顯然也意識到了這個問題,於是補上了明確指定父子關係的初始化方式:
- (void)viewDidLoad {
[super viewDidLoad];
progress = [NSProgress progressWithTotalUnitCount:10];
[progress addObserver:self
forKeyPath:@"fractionCompleted"
options:NSKeyValueObservingOptionNew
context:nil];
// 直接宣告父子關係,不再依賴執行緒上下文
NSProgress *sub = [NSProgress progressWithTotalUnitCount:10
parent:progress
pendingUnitCount:5];
NSProgress *sub2 = [NSProgress progressWithTotalUnitCount:10
parent:progress
pendingUnitCount:5];
for (int i = 0; i < 10; i++) {
sub.completedUnitCount++;
sub2.completedUnitCount++;
}
}
結構清楚許多,也不必再操心註冊與取消註冊的配對。
// 取得當前執行緒的根節點(需先有物件呼叫過 becomeCurrent...)
+ (nullable NSProgress *)currentProgress;
// 建立進度物件
+ (NSProgress *)progressWithTotalUnitCount:(int64_t)unitCount;
// iOS 9 起:不依附於當前上下文,獨立建立
+ (NSProgress *)discreteProgressWithTotalUnitCount:(int64_t)unitCount;
// iOS 9 起:明確指定父節點
+ (NSProgress *)progressWithTotalUnitCount:(int64_t)unitCount
parent:(NSProgress *)parent
pendingUnitCount:(int64_t)portionOfParentTotalUnitCount;
// 實例初始化,parent 可為 nil
- (instancetype)initWithParent:(nullable NSProgress *)parentProgressOrNil
userInfo:(nullable NSDictionary *)userInfoOrNil;
// 註冊/取消註冊為當前執行緒的根節點,必須成對使用
- (void)becomeCurrentWithPendingUnitCount:(int64_t)unitCount;
- (void)resignCurrent;
// iOS 9 起:以程式碼為既有節點掛上子節點
- (void)addChild:(NSProgress *)child withPendingUnitCount:(int64_t)inUnitCount;
@property int64_t totalUnitCount; // 總單元數
@property int64_t completedUnitCount; // 已完成單元數
@property (getter=isCancellable) BOOL cancellable;
@property (getter=isPausable) BOOL pausable;
@property (readonly) double fractionCompleted; // 0~1
- (void)cancel;
- (void)pause;
- (void)resume;
// 設定預估剩餘時間,會反映到 localizedAdditionalDescription
// 例如:0 of 10 — About 10 seconds remaining
[progress setUserInfoObject:@10 forKey:NSProgressEstimatedTimeRemainingKey];
// 設定處理速率
// 例如:Zero KB of 10 bytes (15 bytes/sec)
[progress setUserInfoObject:@15 forKey:NSProgressThroughputKey];
// 以下鍵值需先把 kind 設為 NSProgressKindFile 才會生效
[progress setUserInfoObject:NSProgressFileOperationKindDownloading
forKey:NSProgressFileOperationKindKey];
// 檔案總數,例如:Copying 100 files…
[progress setUserInfoObject:@100 forKey:NSProgressFileTotalCountKey];
[progress setUserInfoObject:@1 forKey:NSProgressFileCompletedCountKey];
NSProgressFileOperationKindKey 會影響 localizedDescription 的文字,可選值對應的提示語分別是 Downloading files…、Decompressing files…、Receiving files… 與 Copying files…。
1. 在啟動長時間任務之前,先用 progressWithTotalUnitCount: 建立物件。totalUnitCount 要從「UI 需要幾次更新」的角度來估算,而不是糾結於底層實際處理了多少位元組或多少筆資料。如果只是遍歷集合並逐項更新,那麼這個值往往就是集合的數量。
2. 用 KVO 監聽 fractionCompleted。在 macOS 上可以直接透過 Cocoa Bindings 綁到進度條,在 iOS 則需要自己在 observer 回呼中更新 UI。除了 fractionCompleted,localizedDescription 與 localizedAdditionalDescription 也很適合綁到文字標籤上。特別注意:KVO 通知是在「修改屬性的那個執行緒」上送出的,因此更新 UI 前請自行切回主執行緒。
3. 以 becomeCurrentWithPendingUnitCount: 建立子進度,pendingUnitCount 代表「這段程式碼將占整體工作的多少」。若工作被拆成多段,可以多次呼叫並各自傳入占比。
4. 呼叫實際的工作方法。由於「當前進度」是執行緒區域的概念,這一步必須和 becomeCurrentWithPendingUnitCount: 在同一個執行緒進行。若 UI 層把任務丟到背景佇列同步執行,請務必讓這兩個呼叫位在同一個 dispatch_async 區塊內。
5. 最後呼叫 resignCurrent 收尾。它與 becomeCurrentWithPendingUnitCount: 成對,次數必須一致;而且不必等到工作真正完成才呼叫,可以提前解開註冊。