Dealing with crashes

Your application is going to crash! A Cocoa application will usually crash for the following reasons:

  • Low memory crash: This happens when your app uses too much system RAM and the system kills it
  • Bad memory access (EXC_BAD_ACCESS): This happens if you try to access an object at a memory address where it isn't
  • Abnormal Exit (SIGABRT): This happens if your app takes too long to launch or an exception isn't caught properly
  • Bad instruction (EXC_BAD_INSTRUCTION): You have tried to give the app an instruction that the compiler doesn't understand

When a crash happens, Xcode will attempt to give you as much information as it can in order to help you fix the issue. First, the system will highlight the offending line of code that caused the error in the standard editor. To the left, it will show the error type or code that caused it. In many cases, more information will be printed on the console.

The simplest way of crashing an application in Swift is by forcibly unwrapping an optional with a nil value (EXC_BAD_INSTRUCTION). Create a new, single view application called Crash and save it on your Mac.

Open up ViewController.swift and add the following lines of code:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let testConstant:String? = nil
        
        print(testConstant!)
    }
}

Run the application and watch it immediately crash with the EXC_BAD_INSTRUCTION error, like this:

Dealing with crashes

The system highlights the line that caused the crash, and the information on the console hints at what crashed your app:

fatal error: unexpectedly found nil while unwrapping an Optional value

To fix the crash, simply remove the exclamation point from the print statement, as follows:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let testConstant:String? = nil
        
        print(testConstant)
    }
}

The app will run properly and nil will be printed on the console, as shown in this screenshot:

Dealing with crashes
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.143.239