方法 getValue 需延遲返回 CGFloat,但不阻塞調用線程(主線程)。
-(CGFloat)getValue {
// 無法在同步方法中實現非阻塞延遲返回
return floatValue;
}
同步方法必須立即返回,無法「暫停」函數執行。
- (void)asyncGetValueWithCompletion:(void (^)(CGFloat value))completion {
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)); // 2秒延遲
dispatch_after(popTime, dispatch_get_main_queue(), ^{
CGFloat result = [self computeValue]; // 耗時計算或網絡請求
if (completion) completion(result);
});
}
// 調用
[self asyncGetValueWithCompletion:^(CGFloat value) {
// 主線程回調,更新 UI
self.label.text = [NSString stringWithFormat:@"%.2f", value];
}];
使用 PromiseKit、Bolts 或 RxSwift 鏈式異步:
// PromiseKit
- (PMKPromise *)fetchValue {
return [PMKPromise promiseWithResolver:^(PMKResolver resolve, PMKRejecter reject) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 2*NSEC_PER_SEC), dispatch_get_main_queue(), ^{
resolve(@([self computeValue]));
});
}];
}
// 調用
[self fetchValue].then(^(NSNumber *value) {
self.label.text = [NSString stringWithFormat:@"%.2f", value.floatValue];
});
[NSThread sleepForTimeInterval:]、semaphore_wait 會凍結 UI,導致 Watchdog 崩潰 (0x8badf00d)。dispatch_async(dispatch_get_main_queue(), ...)。self 需用 __weak typeof(self) weakSelf = self;。voidcompletion:(void(^)(ResultType))block 參數block(result)「延遲返回不阻塞」本質是同步轉異步,Block 回調是 Objective-C 基礎模式,Swift 推薦 async/await 或 Combine。