Reputation: 7456
For some reason when I use self.window?.makeKeyAndView()
in my AppDelegate, I get the EXC_Breakpoint. When I let the ViewController load in normally via Segue, it doesn't happen.
Basically, my goal with this code is to skip the initial view controller if the user is already logged in.
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
:
This is a chunk of code in my 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)
When I comment out the line that triggers is the one I commented on, then the next equivalent View 2 string one triggers it. I don't understand why this is happening.
Edit:
I fixed it as follows:
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
}
Upvotes: 0
Views: 690
Reputation: 119242
You need to show more information, like the stack trace and anything additional from the console.
However in this case your problem is clear. You make a new view controller by initialising it directly (MainViewController()
) when you do this none of the information from your storyboard is present, so all of your outlets will be nil, and since they are implicitly unwrapped optionals (!
) this causes a crash.
The explanation for the crash is clearly printed in the console.
If the content of a VC is defined on the storyboard, you have to load it from the storyboard. Use instantiateViewControllerWithIdentifier
.
Upvotes: 2