0

我正在制作一个对多个文件进行大量计算的应用程序,因此为了跟踪正在发生的一切,我添加了一个 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

为什么进度条不更新?它在主线程上运行。

4

1 回答 1

4

看起来你正在做整数数学,这永远不会产生浮点值。你必须将你的价值观作为一个double做你想做的事。

double progress = (((double)i) + 1.0) / ((double)_files.count);
[_progressBar setDoubleValue:progress * 100.0];

还值得一提的是,如果适当地设置进度条的minValueand (默认为 0.0 和 100.0) ,则不必乘以100.0。maxValue您很可能希望将其放入viewDidLoad

[_progressBar setMinValue:0.0];
[_progressBar setMaxValue:1.0];
于 2015-10-09T22:25:40.250 回答