在 iOS 7 之前,系統並沒有一個統一的框架來描述「任務進度」,開發者得自己發明一套進度回報機制,跨模組溝通相當麻煩。iOS 7 之後推出的 NSProgress 類徹底改變了這件事——它以樹狀結構設計,能優雅地表達「一個大任務由多個子任務組成」這種層級關係。
這是最簡單的場景。我們用 NSTimer 模擬一個耗時任務,透過 KVO 監聽 fractionCompleted 的變化:
@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 {
// 每完成一個單元就 +1
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;
現實中的任務往往還有子任務,例如「下載 10 個檔案」本身是個任務,每個檔案的下載又是子任務。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];
int i = 0;
while (i < 10) {
i++;
sub.completedUnitCount++;
}
}
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context {
NSLog(@"= %@", progress.localizedAdditionalDescription);
}
@end
這裡有個關鍵觀念必須理解:becomeCurrentWithPendingUnitCount: 的作用是「把這個 NSProgress 物件註冊為當前執行緒的根進度物件」,resignCurrent 則是取消註冊。這兩個方法必須成對出現。而當某個物件成為當前執行緒的根節點後,後續用類方法 progressWithTotalUnitCount: 建立的物件,都會自動被掛成它的子節點——這正是樹狀結構得以成形的機制。
必須承認,註冊根節點這種「靠執行緒隱含狀態」的設計可讀性不佳,程式碼意圖不明。Apple 顯然也意識到了這點,在 iOS 9 中補上了顯式指定父子關係的方法:
- (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++;
}
}
新寫法把層級關係寫在呼叫端,程式碼結構一目了然,可操作性也更好。新專案建議直接採用這種形式。
// 取得當前執行緒的進度管理根節點
// 注意:必須先有物件呼叫過 becomeCurrentWithPendingUnitCount: 才抓得到
+ (nullable NSProgress *)currentProgress;
// 建立 NSProgress 物件
+ (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;
NSProgress 的 userInfo 字典提供了一批系統預約的鍵,可用來微調格式化輸出的內容:
// 設定剩餘時間,會影響 localizedAdditionalDescription
// 例如:0 of 10 — About 10 seconds remaining
[progress setUserInfoObject:@10 forKey:NSProgressEstimatedTimeRemainingKey];
// 設定處理速度,同樣影響 localizedAdditionalDescription
// 例如:Zero KB of 10 bytes (15 bytes/sec)
[progress setUserInfoObject:@15 forKey:NSProgressThroughputKey];
/* 以下鍵值生效的前提是:必須先把 kind 設為 NSProgressKindFile */
// 操作類型,會影響 localizedDescription
// NSProgressFileOperationKindDownloading → Downloading files…
// NSProgressFileOperationKindDecompressingAfterDownloading → Decompressing files…
// NSProgressFileOperationKindReceiving → Receiving files…
// NSProgressFileOperationKindCopying → Copying files…
[progress setUserInfoObject:NSProgressFileOperationKindDownloading
forKey:NSProgressFileOperationKindKey];
// 檔案總數,例如:Copying 100 files…
[progress setUserInfoObject:@100 forKey:NSProgressFileTotalCountKey];
// 已完成的檔案數
[progress setUserInfoObject:@1 forKey:NSProgressFileCompletedCountKey];
步驟一:建立 NSProgress 實例。在啟動長時間任務之前,用 progressWithTotalUnitCount: 建立物件。這裡的 totalUnitCount 代表「要完成的總工作單元數」。
關於這個數字有個重要觀念:要從 UI 層的角度去理解它,而不是糾結背後有幾個真實的工作物件。你不會被要求猜測工作單元的物理意義(位元組?像素?文字行數?)。如果你打算遍歷集合、為每個元素呼叫一次,那這個值通常就是 1 或集合元素的數量。
步驟二:用 KVO 監聽 fractionCompleted。NSProgress 與 NSOperation 一樣,是為 KVO 而設計的。在 macOS 上,這讓你能透過 Cocoa Bindings 直接把 NSProgress 綁到進度條或標籤上;在 iOS 上則需要你在 KVO 回呼中手動更新 UI。
除了 fractionCompleted,還有 completedUnitCount 與 totalUnitCount;而 localizedDescription(例如「50% completed」)與 localizedAdditionalDescription(例如「3 of 6」)也很適合用來更新文字標籤。特別注意:KVO 通知是在改變屬性的那個執行緒上送出的,因此更新 UI 前請確認自己身在主執行緒。
步驟三:用 becomeCurrentWithPendingUnitCount: 建立子進度。這裡的 pendingUnitCount 代表「即將由接收者完成的總工作單元中的一部分」。你可以多次呼叫,每次傳入整體的一部分。在遍歷集合的範例中,每次迭代都呼叫一次 [progress becomeCurrentWithPendingUnitCount:1]。
步驟四:呼叫工作物件的方法。由於「當前進度」是一個執行緒區域的概念,你必須在呼叫 becomeCurrent 的同一個執行緒上執行實際工作。若工作物件的 API 設計為在主執行緒呼叫,這不成問題。但假如你的 UI 層正在建立背景佇列並把工作丟進去同步執行,就必須確保 becomeCurrentWithPendingUnitCount: 與 resignCurrent 被放在同一個 dispatch_async() 區塊裡。
步驟五:呼叫 resignCurrent。它與 becomeCurrent 成對,呼叫次數必須相同。你不需要等到實際工作完成才呼叫——可以在工作還在進行中就 resignCurrent,讓進度物件的關係如期閉合。