在 iOS 中,當(dāng)使用
-(void)presentViewController:(UIViewController*)viewControllerToPresent animated:(BOOL)flag completion:(void (^__nullable)(void))completion
方法進(jìn)行界面跳轉(zhuǎn)的時(shí)候,有時(shí)候會(huì)出現(xiàn)延遲,這個(gè)延遲有時(shí)候會(huì)有好幾秒的時(shí)間才會(huì)執(zhí)行 completion,有時(shí)候干脆就一直不會(huì)跳轉(zhuǎn)。
例如:在tableview的點(diǎn)擊方法中執(zhí)行
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[self presentViewController:alertViewController animated:YEScompletion:^{
}];
}
alertViewController 跳轉(zhuǎn)延遲很長(zhǎng)時(shí)間,有時(shí)候干脆就不跳轉(zhuǎn)了。但讓人頭疼的是點(diǎn)擊cell的時(shí)候,在alertViewController跳轉(zhuǎn)延遲過(guò)程中,滑動(dòng)一下tableview或者再次點(diǎn)擊一下cell,alertViewController會(huì)立即跳轉(zhuǎn)。
查找了很長(zhǎng)時(shí)間,總算得出一個(gè)原因:由于某種原因,presentViewController跳轉(zhuǎn)時(shí)completion的內(nèi)容并不會(huì)真的馬上觸發(fā)執(zhí)行,除非有一個(gè)主線程事件觸發(fā)這種消費(fèi)。比如在彈出慢的時(shí)候,你隨便點(diǎn)擊一下屏幕,馬上就能彈出來(lái) 。
所以得出相應(yīng)的解決方法:
1.在主線程中執(zhí)行跳轉(zhuǎn):
__weak typeof(self)weakSelf = self;
dispatch_async(dispatch_get_main_queue(), ^(void){
[weakSelf presentViewController:alertViewController animated:YES completion:nil];
});
2.在執(zhí)行跳轉(zhuǎn)前喚醒主線程。
/** WakeUpTheMainThread 方法什么都不執(zhí)行,它的作用只是喚醒主線程 */
[self performSelectorOnMainThread:@selector(WakeUpTheMainThread) withObject:nil waitUntilDone:NO];