在循环期间更新UIProgressBar进度

时间:2014-07-11 15:46:00

标签: ios multithreading uiprogressbar

我无法找到关于如何在迭代循环时更新UIProgressbar的进度的明确答案,例如:

for (int i=0;i<items.count;i++) {
    Object *new = [Object new];
    new.xxx = @"";
    new...
    ...
    float progress = (i+1) / (float)items.count;
    progressBar.progress = progress;
}
[self save];

如何在单独的线程上更新UI?

1 个答案:

答案 0 :(得分:1)

在后台线程上运行循环,并更新主线程上的进度条:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
    for (int i=0;i<items.count;i++) {
        Object *new = [Object new];
        new.xxx = @"";
        new...
        ...
        float progress = (i+1) / (float)items.count;
        dispatch_async(dispatch_get_main_queue(), ^{
            progressBar.progress = progress;
        });

    }
    [self save];
});