You need to enable JavaScript to run this app. Swift退出登录切换rootViewController时出现EXC_BAD_ACCESS错误如何解决
优惠活动
大模型
产品
解决方案
定价
更多

Swift退出登录切换rootViewController时出现EXC_BAD_ACCESS错误如何解决

退出登录切换rootViewController触发内存错误

我尝试使用Swift代码切换rootViewController以实现退出登录功能,运行时出现了内存错误:
错误代码截图

退出登录逻辑代码

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    guard let section = SettingsSection(rawValue: indexPath.section) else { return }
    
    switch section {
    case .Profile:
        print(ProfileOptions(rawValue: indexPath.row)?.description)
        if ProfileOptions(rawValue: indexPath.row)?.description == "Log Out" {
            //logoutTapped()
            //return
            userDefaults.set("", forKey: Keys.username)
            userDefaults.set("", forKey: Keys.useremail)
            
            let storyboard = UIStoryboard(name: "Main", bundle: nil)
            let loginNavController = storyboard.instantiateViewController(identifier: "LoginNavController")
            (UIApplication.shared.connectedScenes.first?.delegate as? SceneDelegate)?.changeRootViewController(loginNavController)
        }
        break
        
    case .Application:
        print(ApplicationOptions(rawValue: indexPath.row)?.description)
    }
}

SceneDelegate 切换根控制器实现代码

func changeRootViewController(_ vc: UIViewController, animated: Bool = true) {
    guard let window = self.window else {
        return
    }
    window.rootViewController = vc
    // add animations
    UIView.transition(with: window,
                      duration: 0.5,
                      options: [.transitionCurlDown],
                      animations: nil,
                      completion: nil)
}

参考了登录界面向标签栏控制器跳转的相关实现教程,求排查思路与解决方案。

排查方向与解决方案

  • 排查userDefaults的引用问题:若你使用的是自定义封装的userDefaults对象,确认其为强引用持有,可直接替换为UserDefaults.standard.set(_:forKey:)测试,若崩溃消失则说明是自定义对象被提前释放导致的内存访问错误。
  • 修正活跃场景的获取逻辑:connectedScenes.first在多场景下可能获取到非当前活跃的场景,替换为以下代码获取前台活跃的SceneDelegate:
    guard let activeScene = UIApplication.shared.connectedScenes.first(where: { $0.activationState == .foregroundActive }),
          let sceneDelegate = activeScene.delegate as? SceneDelegate else { return }
    sceneDelegate.changeRootViewController(loginNavController)
    
  • 延迟切换时机:避免在didSelectRowAt回调未完全结束时就切换根控制器,可在主线程稍作延迟后执行切换:
    DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
        sceneDelegate.changeRootViewController(loginNavController)
    }
    
  • 确认SceneDelegate的window初始化正确:若使用SceneDelegate架构,需在scene(_:willConnectTo:options:)方法中手动初始化并持有window,示例:
    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        guard let windowScene = scene as? UIWindowScene else { return }
        self.window = UIWindow(windowScene: windowScene)
        self.window?.makeKeyAndVisible()
        // 配置初始根控制器
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.19 13:54:04