You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中同一视图控制器下Segue与Unwind Segue共存报错排查

解决MoonViewController返回Earth时的Unwind Segue SIGABRT错误

你遇到的Thread 1: Signal SIGABRT崩溃根源很明确——你的MoonViewController里的prepare(for:sender:)方法存在逻辑漏洞:

你现在是无条件地把所有segue的destination强制转换为JupiterViewController,但当触发从Moon回到Earth的unwind segue时,这个segue的目标控制器其实是ViewController(也就是Earth页面),强制转换as!发现类型不匹配,直接引发崩溃。

修复步骤很简单:

  1. 先通过segue的identifier判断当前处理的是哪一个segue,只在跳转到Jupiter的时候才做类型转换
  2. 用可选绑定代替强制解包,避免类型不匹配时崩溃

修改后的MoonViewController的prepare方法应该是这样的:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    // 只处理跳转到Jupiter的segue
    if segue.identifier == "toJupiterView" {
        // 用可选绑定安全转换目标控制器类型
        if let des = segue.destination as? JupiterViewController {
            print("Went to Jupiter")
        }
    }
}

额外提醒:

  • 永远不要滥用as!强制解包,除非你100%确定类型一定匹配,否则优先用as?配合可选绑定
  • 所有segue(包括unwind segue)都会触发prepare(for:sender:)方法,所以必须通过identifier区分不同的segue逻辑,不能一概而论
  • 最后再检查一下Storyboard里的unwind segue配置:确保从Moon的返回按钮是正确拖到ViewController的backFromMoon方法上,没有选错目标控制器或者方法

内容的提问来源于stack exchange,提问作者JustWorkAlready

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:06:16