EXC_BREAKPOINT 当使用 self.window?.makeKeyAndView()

EXC_BREAKPOINT when using self.window?.makeKeyAndView()

出于某种原因,当我在我的 AppDelegate 中使用 self.window?.makeKeyAndView() 时,我得到了 EXC_Breakpoint。当我让 ViewController 通过 Segue 正常加载时,它不会发生。

基本上,如果用户已经登录,我使用此代码的目标是跳过初始视图控制器。

AppDelegate.swift:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    if NSUserDefaults.standardUserDefaults().objectForKey("auth_token") != nil {
        self.window?.rootViewController = MainViewController()
        self.window?.makeKeyAndVisible()
    }

    return true
}

MainViewController.swift:

这是我viewDidLoad()中的一段代码:

navTitleLabel1 = UILabel()
navTitleLabel1.frame = CGRect(x: 0, y: 8, width: wBounds, height: 20)
navTitleLabel1.text = "View 1" //TRIGGERS EXC_BREAKPOINT (EXC_ARM_BREAKPOINT)
navTitleLabel1.textColor = UIColor.whiteColor()
navTitleLabel1.textAlignment = NSTextAlignment.Center
self.navbarView.addSubview(navTitleLabel1)

navTitleLabel2 = UILabel()
navTitleLabel2.alpha = 0.0
navTitleLabel2.frame = CGRect(x: 100, y: 8, width: wBounds, height: 20)
navTitleLabel2.text = "View 2"
navTitleLabel2.textColor = UIColor.whiteColor()
navTitleLabel2.textAlignment = NSTextAlignment.Center
self.navbarView.addSubview(navTitleLabel2)

当我注释掉触发的那一行时,下一个等效的 View 2 字符串将触发它。我不明白为什么会这样。

编辑:

我修改如下:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    if NSUserDefaults.standardUserDefaults().objectForKey("auth_token") != nil {
        var storyboard = UIStoryboard(name: "Main", bundle: nil)

        self.window!.rootViewController = storyboard.instantiateViewControllerWithIdentifier("MainViewController") as? UIViewController

        self.window?.makeKeyAndVisible()
    }

    return true
}

您需要显示更多信息,例如堆栈跟踪和控制台中的任何其他信息。

但是在这种情况下,您的问题很明显。当你这样做时,你通过直接初始化它(MainViewController())来创建一个新的视图控制器选项 (!) 这会导致崩溃。

崩溃的解释清楚地打印在控制台中。

如果VC的内容定义在情节提要上,您必须从情节提要中加载它。使用 instantiateViewControllerWithIdentifier