尝试更改根视图控制器时 App Delegate 因 NSException 而崩溃

App Delegate crashes with NSException when trying to change root view controller

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

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: terminating with uncaught exception of type NSException (lldb)

提前致谢。

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

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