NSProgressIndicator进展与For循环? [英] NSProgressIndicator progress with For loops?

查看:82
本文介绍了NSProgressIndicator进展与For循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序通过一堆For循环做了很多工作.它计算了大量的字符串,并且可能需要一整分钟才能完成.

My application does a lot of work with a bunch of For loops. It calculates a massive amount of strings, and it can take over a whole minute to finish.

所以我在应用程序中放置了一个NSProgressIndicator.

So I placed a NSProgressIndicator in my app.

在循环中,我使用了NSProgressIndicator的"incrementBy"功能.但是,我看不到实际的条形填充.

Within the loops, I used the "incrementBy" function of the NSProgressIndicator. However, I don't see the actual bar filling up.

我怀疑这是因为循环可能会消耗所有能量,因此NSProgressIndicator不会(以图形方式)更新.

I suspect that's because of the loops taking all power possible, and thus the NSProgressIndicator is not updated (graphically).

那我该如何进步?

推荐答案

您的for循环是否在主线程或后台线程上运行?如果它们在主线程上运行,则GUI将永远没有机会更新自身以反映进度变化,因为这只会在runloop的末尾(即,函数完成运行之后)发生.

Are your for loops running on the main thread or in a background thread? If they're running on the main thread, the GUI will never get a chance to update itself to reflect the progress change as this will only happen at the end of the runloop, i.e. after your functions have finished running.

如果您的for循环在后台运行,则您很顽皮!除了主线程外,您不应该从任何地方更新GUI.如果您的目标是现代系统,则可以使用GCD轻松解决此问题.

If your for loops are running in the background, you're being naughty! You shouldn't update the GUI from anywhere but the main thread. If you're targeting a modern system, you can use GCD to trivially work around this.

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) {
    for (int i = 0; i < n; i++) {
        // do stuff
        dispatch_async(dispatch_get_main_queue(), ^(void) {
            // do your ui update here
        });
    }
});

或者,您可以重写for循环以进一步利用GCD并使用dispatch_apply.上面的等价于:

Alternatively, you can rewrite your for loops to take advantage of GCD even further and use dispatch_apply. The equivalent of the above would be:

dispatch_apply(n, DISPATCH_QUEUE_PRIORITY_DEFAULT, ^(size_t i) {
    // for loop stuff here
    dispatch_async(dispatch_get_main_queue(), ^(void) {
        // do your ui update here
    });
});

请注意,使用 dispatch_apply 表示循环的每个迭代"都可以相对于彼此并发运行,因此,如果您的for循环需要以串行方式运行,则该循环将不适用

Note that using dispatch_apply means that each "iteration" of the loop may run concurrently with respect to one another, so this won't be applicable if your for loop requires to be run in a serial fashion.

这篇关于NSProgressIndicator进展与For循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆