updating UIProgressBar progress during loop

半腔热情 提交于 2019-12-12 04:06:15

问题


I can't find a clear answer on how to update the progress of a UIProgressbar whilst iterating a loop e.g. :

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];

how can I update the UI on a seperate thread?


回答1:


Run the loop on a background thread, and update the progress bar on the main thread:

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];
});


来源:https://stackoverflow.com/questions/24701643/updating-uiprogressbar-progress-during-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!