由于某种原因,当我在AppDelegate中使用self.window?.makeKeyAndView()
时,得到了EXC_Breakpoint。当我通过Segue正常加载ViewController时,它不会发生。
基本上,我使用此代码的目标是,如果用户已经登录,则跳过初始视图控制器。
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
。