0

我正在使用 GCD 在后台运行一些代码。该操作在几秒钟内完成,最后按预期打印“DONE”。但是,我必须等待 ~5 秒(模拟器)到 ~1 分钟(设备)才能隐藏 hud。如此长时间的延迟可能是什么原因?我知道处理已经完成,因为我可以看到每个元素的结果。

MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
hud.mode = MBProgressHUDModeAnnularDeterminate;
dispatch_group_t group = dispatch_group_create();
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH,0);

NSArray *keys = [NSArray arrayWithArray: [codePositions allKeys]];
for (id key in keys) {
    if (key == nil)
        continue;
    dispatch_group_async(group, queue, ^{
        ... // processing
        NSLog(@"Element %d result: %@", element.id, element.result);
        hud.progress += 1.0/96.0;
    });
}
dispatch_group_notify(group, queue, ^{
    NSLog(@"DONE");
    [hud hide:YES];
});

谢谢你的时间。

4

1 回答 1

3

您需要在主线程上执行所有 UI 更新。更新您的代码如下:

for (id key in keys) {
    if (key == nil)
        continue;
    dispatch_group_async(group, queue, ^{
        ... // processing
        NSLog(@"Element %d result: %@", element.id, element.result);
        dispatch_async(dispatch_get_main_queue(), ^{
            hud.progress += 1.0/96.0;
        });
    });
}
dispatch_group_notify(group, queue, ^{
    NSLog(@"DONE");
    dispatch_async(dispatch_get_main_queue(), ^{
        [hud hide:YES];
    });
});
于 2013-05-21T16:30:59.413 回答