首页 > 解决方案 > 尝试更改根视图控制器时,App Delegate 崩溃并出现 NSException

问题描述

第一次运行应用程序后尝试更改根视图控制器,但它崩溃了。

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        if(UserDefaults.standard.bool(forKey: "notFirstInApp") == false){
            UserDefaults.standard.set(true, forKey: "notFirstInApp")
            let state = StateTableViewController()
            window?.rootViewController = state
        }else{
            let home = HomeViewController()
            window?.rootViewController = home
        }

        return true
    }

崩溃与

libc++abi.dylib:以 NSException (lldb) 类型的未捕获异常终止

提前致谢。

标签: iosswiftappdelegate

解决方案


您不能通过 viewController 名称直接设置 rootViewController。请检查以下代码

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let initialViewController = storyboard.instantiateViewController(withIdentifier: "LoginSignupVC")
self.window?.rootViewController = initialViewController
self.window?.makeKeyAndVisible()

推荐阅读