我正在制作一个对多个文件进行大量计算的应用程序,因此为了跟踪正在发生的一切,我添加了一个 NSProgressIndicator(值 0-100)。
我在应用程序中也有一个控制台,因此该logConsole:
方法会写入该控制台。
我的循环如下所示:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
for(int i = 0; i < _files.count; i++)
{
//Do calculations
dispatch_async(dispatch_get_main_queue(), ^(void){
[_progressBar setDoubleValue: ((i+1) / _files.count) * 100];
[self logConsole:[NSString stringWithFormat:@"Completed file #%d", (i+1)]];
});
}
});
当此循环运行时,消息会异步记录到应用程序的控制台(不是 NSLog,我创建的实际 GUI 控制台),但在整个 for 循环完成之前进度条不会改变。
因此,如果有 5 个文件,它将如下所示:
LOG: Completed file #1
Progress bar at 0
LOG: Completed file #2
Progress bar at 0
LOG: Completed file #3
Progress bar at 0
LOG: Completed file #4
Progress bar at 0
LOG: Completed file #5
Progress bar at 100
为什么进度条不更新?它在主线程上运行。