2013-05-21 44 views
0

我正在使用GCD在後臺運行一些代碼。操作在幾秒鐘內完成,最後按預期打印「完成」。但是我必須等待約5秒鐘(模擬器)〜1分鐘(裝置)以隱藏。造成這麼長時間的原因可能是什麼?我知道處理已完成,因爲我可以看到每個元素的結果。iOS - GCD組和完成時的重要UI延遲

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

謝謝你的時間。

回答

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

工程就像一個魅力。謝謝。 – Jacek