Push与present切换页面可能发送的崩溃, 分析与解决.
Push的报错
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Pushing the same view controller instance more than once is not supported (<UIViewController: 0x7fd100f0e890>)'
基本上发生原因解释的很清楚, push了两次同一个UIViewController导致的.
解决方案:
guard navigationController?.viewControllers.contains(vc) == false else { return }
发生原因
并不是每次都会在点击的时候创建UIViewController然后push, 有时候UIViewController会在前一页持有, 点击的时候进行push. 这时候有可能由于卡顿/通知调用/线程等原因, 造成push两次事件而崩溃.
Present崩溃
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Application tried to present modally an active controller <CoreAnimation.ViewController: 0x7fa4d4703b40>.'
原因基本同上, 发生情景也类似.
解决方案
guard vc.isBeingPresented == false else { return }
// 判断一下当前vc是否已经被Presented出来了
建议用法
extension UIViewController {
func present(_ vc: UIViewController, _ animated: Bool, _ completion: (() -> Void)? = nil) {
guard false == vc.isBeingPresented else { return }
present(vc, animated: animated, completion: completion)
}
func push(_ vc: UIViewController, animated: Bool){
guard false == navigationController?.viewControllers.contains(vc) else { return }
navigationController?.pushViewController(vc, animated: animated)
}
}
// 简书排版看着不舒服来张图
More
有的同学可能会想dissmiss/pop时候会不会也崩溃? 我暂时测试没出来, 有出来欢迎留言反馈.