Terminating app due to uncaught exception 'NSInvalidArgumentException'

Push与present切换页面可能发送的崩溃, 分析与解决.

Push的报错
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Pushing the same view controller instance more than once is not supported ()'

基本上发生原因解释的很清楚, push了两次同一个UIViewController导致的.


Terminating app due to uncaught exception 'NSInvalidArgumentException'_第1张图片
Push两次同一个ViewController

解决方案:

  guard navigationController?.viewControllers.contains(vc) == false else { return }
检查是否已经存在与当前navigationControllers

发生原因

并不是每次都会在点击的时候创建UIViewController然后push, 有时候UIViewController会在前一页持有, 点击的时候进行push. 这时候有可能由于卡顿/通知调用/线程等原因, 造成push两次事件而崩溃.

Present崩溃
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Application tried to present modally an active controller .'

原因基本同上, 发生情景也类似.


Terminating app due to uncaught exception 'NSInvalidArgumentException'_第2张图片
多次present同一个ViewController

解决方案

  guard vc.isBeingPresented == false else { return }
  // 判断一下当前vc是否已经被Presented出来了
Terminating app due to uncaught exception 'NSInvalidArgumentException'_第3张图片
屏幕快照 2018-06-30 15.38.28.png

建议用法

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

// 排版看着不舒服来张图


Terminating app due to uncaught exception 'NSInvalidArgumentException'_第4张图片
给UIViewController加个扩展

More

有的同学可能会想dissmiss/pop时候会不会也崩溃? 我暂时测试没出来, 有出来欢迎留言反馈.

你可能感兴趣的:(Terminating app due to uncaught exception 'NSInvalidArgumentException')