Skip to content
Commitwise
Menu
iOS Development

Crashes and debugging in production

Read an iOS crash report, symbolicate it, recognize the common exception types (Swift traps, bad memory access, uncaught exceptions, watchdog and memory terminations), and find causes you can't reproduce with sanitizers, Zombies, logs and MetricKit diagnostics.

advanced

The core idea with one simple example.Step by step, with more examples and exercises.A cheat sheet: key APIs, gotchas and trade-offs.Internals, trade-offs and production pitfalls.

The new release has a crash rate of 0.4%. The top crash is EXC_BAD_ACCESS in a Dictionary method, on many devices and OS versions, and nobody on the team can reproduce it. The second is EXC_BREAKPOINT in CheckoutViewModel.total.getter. The third doesn’t appear in the crash reporter at all: users write that “the app closes when I scroll the photo library”, and the support team can’t tell if it’s the same problem.

Crashes are where senior engineers earn their reputation: not by never shipping one, but by reading a report, forming a hypothesis and fixing the real cause instead of adding a guard around the symptom. This lesson is the toolkit: what a crash report says, what each kind of crash usually means, and how to hunt the ones you can’t reproduce.

New to some of these? Open what you need, or skip ahead.

Basics:What is a stack trace?

A stack trace (or backtrace) is the list of functions that were running at a moment, newest first: total.getter was called by body, which was called by SwiftUI, and so on. In a crash report, the stack trace of the crashed thread shows where the app was when it stopped. Each line is a frame.

Basics:Debug and release builds

Xcode’s Run button builds the Debug configuration: no compiler optimizations, extra checks. The App Store gets a Release build: optimized, so functions may be inlined (merged into their callers) and some frames disappear from stack traces. Some bugs, especially timing bugs, show up only in release builds.

Part Not started

Reading a crash report

A crash report is like the black box of a plane. It tells you:

  1. Which app version and device: the header. A crash only on one OS version, or only on old devices, is already a clue.
  2. What kind of crash: the exception type. Different types mean very different problems (see the table below).
  3. Where: the backtrace of the crashed thread. Read it from the top: the first frames from your code are usually the most interesting.

You’ll see reports in Xcode → Window → Organizer → Crashes (from users who share diagnostics with developers) and in crash reporting services like Crashlytics or Sentry, which collect more of them and group them.

For function names and line numbers, the report needs the dSYMdSYMA file with the debug symbols of one exact build, used to turn crash report addresses into function names and line numbers.Open in glossary → of exactly that build: a file Xcode creates when it archives the app, which maps memory addresses back to your code. This is called symbolication. Without it you only see addresses like 0x0000000102a4c3f8.

The report’s header (version, build, OS, device model, launch time vs crash time) narrows the population; the exception type and codes plus termination reason classify the failure; the crashed thread’s backtrace locates it; the other threads and the binary images section (load addresses and UUIDs) explain context and allow manual symbolication (atos -arch arm64 -o App.dSYM/Contents/Resources/DWARF/App -l <load address> <address>). Symbolication requires the dSYM whose UUID matches the binary; upload dSYMs from CI for every archive (Crashlytics, Sentry), since bitcode and App Store recompilation no longer apply. Release builds inline aggressively, so the top frame of yours may be a caller of the real culprit, and line numbers can point near, not at, the failing check. In .ips JSON (iOS 15+) the same fields are machine-readable. Note what a crash report can’t show: terminations by the system (jetsam, some watchdog kills, background task expirations) appear only as termination reasons in MetricKit and the Organizer’s Terminations report, not as crashes.

// CheckoutViewModel.swift:48
var total: Decimal {
    items.reduce(0) { $0 + prices[$1.productID]! * Decimal($1.quantity) }   // a price missing from the dictionary
}
Incident Identifier: 6F1A…
Hardware Model:      iPhone14,5
Version:             4.12 (1287)
OS Version:          iPhone OS 18.3.1 (22D72)

Exception Type:  EXC_BREAKPOINT (SIGTRAP)
Exception Codes: 0x0000000000000001, 0x00000001a2b5e8f4
Termination Reason: SIGNAL 5 Trace/BPT trap: 5

Thread 0 name:  Dispatch queue: com.apple.main-thread
Thread 0 Crashed:
0   libswiftCore.dylib   _assertionFailure(_:_:file:line:flags:) + 244
1   Shop                 CheckoutViewModel.total.getter + 312 (CheckoutViewModel.swift:48)
2   Shop                 CheckoutView.body.getter + 1020 (CheckoutView.swift:31)
3   SwiftUICore          …

Reading it:

  • EXC_BREAKPOINT (SIGTRAP) with _assertionFailure at the top means a Swift safety check failed on purpose: here, a force unwrap (!) found nil.
  • Frame 1 is the first line of your app’s code: CheckoutViewModel.swift:48.
  • Thread 0, the main thread, crashed while SwiftUI was drawing the checkout screen.

The fix is not to replace ! with ?? 0 and move on: a missing price would make the total wrong. Ask why a product in the cart has no price (stale cache? product removed from the catalog?) and handle that case on purpose.

Exception typeUsually meansFirst things to check
EXC_BREAKPOINT (SIGTRAP)A Swift runtime trap: force unwrap of nil, index out of range, integer overflow, fatalError, failed preconditionThe first frame in your code; the line is the failed check
EXC_BAD_ACCESS (SIGSEGV / SIGBUS)Reading or writing invalid memoryData races, unowned references to freed objects, unsafe pointers, C/Objective-C code
EXC_CRASH (SIGABRT)Something called abort(): often an uncaught Objective-C exception“Last Exception Backtrace”: e.g. NSInvalidArgumentException, invalid UITableView updates
0x8badf00d terminationWatchdog: the app didn’t respond in time (launch, resume, background tasks)Synchronous work on the main thread at launch or when returning from background
No crash report, app “just closes”Memory limit (jetsamJetsamThe iOS mechanism that terminates apps using too much memory, without producing a crash report.Open in glossary →) or another system terminationMetricKit exit reasons, Organizer → Terminations, Allocations
Spot the bugA fix that hides the problem

Tap the line with the bug.

// Crash report: EXC_BREAKPOINT in OrderHistoryView.body, "Index out of range"
struct OrderHistoryView: View {
    let orders: [Order]
    let selectedIndex: Int

    var body: some View {
        if selectedIndex < orders.count {
            OrderDetail(order: orders[selectedIndex])
        } else {
            EmptyView()
        }
    }
}

Practice: from report to fix

  1. Group: in the Organizer or your crash reporter, open the top crash. Note how many users, which versions, which OS versions. If it started in one version, compare that version’s changes.
  2. Classify: read the exception type with the table above. EXC_BREAKPOINT points to a Swift check; EXC_BAD_ACCESS to memory or threads.
  3. Locate: find the first frame from your app in the crashed thread. Open that file and line.
  4. Ask why: which value was unexpected (nil, an index, a state)? Where does it come from? Find the path that produces it.
  5. Reproduce if you can: a unit test with that state is the best proof of the fix.
  6. Fix the cause, then watch: after release, check that the crash group stops growing for the new version.

Predict the output

A crash report shows EXC_CRASH (SIGABRT). The "Last Exception Backtrace" contains -[UITableView _endCellAnimationsWithContext:] and the reason says "Invalid update: invalid number of rows in section 0". What happened?

What the top frame doesn’t tell you

  • Optimized frames: inlining can make the crash appear in a caller, and tail calls can remove frames entirely. Check the line numbers of neighbouring frames and, if needed, the disassembly in Xcode with the dSYM.
  • Crashes in system frameworks are almost always caused by how you called them: look for the first frame of yours, on any thread, and for main-thread-only APIs called elsewhere.
  • Memory corruption shows up far from its cause: the crash in Dictionary is where a race was noticed, not where the second writer was. Treat EXC_BAD_ACCESS with KERN_INVALID_ADDRESS near small addresses as nil-ish dereferences in unsafe or Objective-C code, and random-looking addresses as corruption.
  • Duplicates: grouping by top frame merges different bugs and splits one bug across OS versions. Read several reports in a group before concluding.
  • Report: header (version, OS, device), exception type/codes, termination reason, crashed thread backtrace, binary images (UUIDs, load addresses for atos).
  • Symbolication needs the matching dSYM: upload from CI for every archive.
  • EXC_BREAKPOINT: Swift traps (unwrap, bounds, overflow, fatalError). EXC_BAD_ACCESS: invalid memory (races, unowned, unsafe/ObjC). SIGABRT: uncaught ObjC exception (Last Exception Backtrace). 0x8badf00d: watchdog.
  • Jetsam and other system terminations produce no crash report: MetricKit exit reasons, Organizer Terminations.
  • Release inlining moves frames; corruption crashes far from the cause; fix causes, not symptoms.

Check this part

  1. A crash report shows only addresses, no function names. What’s missing?

  2. EXC_BREAKPOINT with _assertionFailure at the top usually means…

  3. Users say the app closes, but there are no crash reports. Likely cause?

  4. What does termination code 0x8badf00d mean?

A crash report has a header (app version, OS, device), the exception type and termination reason, and the crashed thread's backtrace. It needs the build's dSYM to show function names and lines. EXC_BREAKPOINT is usually a Swift runtime trap (force unwrap, index out of range, fatalError); EXC_BAD_ACCESS is invalid memory (often a data race or unsafe code); SIGABRT is an uncaught exception or abort; 0x8badf00d is the watchdog; memory terminations (jetsam) leave no crash report.

Part Not started

Finding causes you can’t reproduce

Some crashes happen once in thousands of sessions. You can’t step through them in the debugger, so you make the tools catch them for you:

When tools can’t reproduce it, collect clues from production:

  • Logs with os.Logger (what the user did just before), which crash reporters attach as breadcrumbs.
  • Patterns in the reports: only one OS version? Only iPads? Only after a certain screen?

Make rare crashes deterministic where possible: TSan in CI unit and UI test runs (with Swift 6 checking, races remaining are in @unchecked Sendable, Objective-C or C code), ASan and UBSan for unsafe code and C dependencies, Zombies (NSZombieEnabled) for Objective-C over-release, the Main Thread Checker and -com.apple.CoreData.ConcurrencyDebug 1 for threading contracts. In production, combine a crash reporter (Crashlytics, Sentry, or MetricKit-based) with breadcrumbs (structured os.Logger events plus custom keys: screen, feature flags, account type), and subscribe to MetricKit MXDiagnosticPayload for crash, hang, CPU and disk-write diagnostics with call stacks, plus MXAppExitMetric for exit reasons (memory limit, watchdog, CPU limit, background task expiration). Triage by when it started (version diff, server change, OS release), who (devices, locales, account states) and what (breadcrumbs). Ship fixes with a regression test, and gate risky features behind remote flags so a bad path can be turned off without an App Store release. Keep the crash-free sessions rate (99.8%+ is a common bar) as a release criterion and stop phased releases when a new crash group grows.

import os
import MetricKit

extension Logger {
    static let checkout = Logger(subsystem: "com.example.shop", category: "checkout")
}

// Breadcrumbs: what happened before a crash (privacy-aware: values are private by default)
Logger.checkout.info("Applied coupon \(coupon.code, privacy: .private) to cart with \(cart.items.count) items")

final class DiagnosticsReceiver: NSObject, MXMetricManagerSubscriber {
    func start() { MXMetricManager.shared.add(self) }

    // Daily aggregates, including why the app was terminated in the foreground and background
    func didReceive(_ payloads: [MXMetricPayload]) {
        for payload in payloads {
            if let exits = payload.applicationExitMetrics?.foregroundExitData {
                report(memoryLimit: exits.cumulativeMemoryResourceLimitExitCount,
                       watchdog: exits.cumulativeAppWatchdogExitCount,
                       badAccess: exits.cumulativeBadAccessExitCount)
            }
        }
    }

    // Crash, hang, CPU and disk-write diagnostics with call stacks
    func didReceive(_ payloads: [MXDiagnosticPayload]) {
        for payload in payloads { upload(payload.jsonRepresentation()) }
    }
}
  • Logger writes to the unified log, which you can read in Console.app from a connected device and which crash reporters can attach. privacy: .private hides the coupon code in logs from users’ devices.
  • foregroundExitData counts how often the app was ended while on screen, by reason. A high cumulativeMemoryResourceLimitExitCount explains “the app just closes” reports that never show up as crashes.
  • MXDiagnosticPayload delivers crash and hang reports with call stacks, collected by iOS.

Predict the output

A crash in the Organizer: EXC_BAD_ACCESS inside Dictionary.subscript.setter, from ImageCache.store(_:for:), on many devices, never reproduced. ImageCache is a class with a [URL: UIImage] dictionary, called from several download tasks. With which tool do you most likely catch it on your own machine?

Production puzzles

Spot the bugThe crash that only happens in release

Tap the line with the bug.

final class SessionManager {
    static let shared = SessionManager()
    private var observers: [UUID: () -> Void] = [:]
    private let queue = DispatchQueue(label: "session", attributes: .concurrent)

    func addObserver(_ block: @escaping () -> Void) -> UUID {
        let id = UUID()
        queue.async { self.observers[id] = block }
        return id
    }

    func notifyAll() {
        queue.sync { observers.values.forEach { $0() } }
    }
}

Predict the output

After a release, the Organizer's Terminations report shows foreground memory-limit exits up 4x on iPhone SE and iPhone 11, and unchanged on Pro models. The release added full-resolution photo previews in a grid. What's the most likely explanation?

Exercisehard

Run the incident

Version 5.2 went out to 20% of users with a 7-day phased release. Two hours in, a new crash group, EXC_BAD_ACCESS in PaymentSheetCoordinator.deinit, has 300 occurrences, all on iOS 17, and it’s the top crash. Walk through the next 24 hours.

›

Separate stopping the damage, finding the cause and shipping the fix, and decide what you can do without an App Store release.

SolutionTry it yourself first
  1. Stop the spread: pause the phased release in App Store Connect. If the payment sheet’s new code path is behind a remote flag, turn it off and watch the crash rate for users who already updated.
  2. Read the reports: several of them, not one. deinit + EXC_BAD_ACCESS suggests something touching the coordinator while or after it’s freed: an unowned reference, a notification or KVO observer not removed, a callback from an SDK on another thread. iOS 17 only points to an OS behavior difference (a system callback, a delegate called later).
  3. Diff 5.2: which changes touched the payment sheet, its delegates or its lifetime? Check breadcrumbs for the steps before the crash.
  4. Reproduce: run the flow on iOS 17 with Zombies and ASan, and with TSan; dismiss the sheet in every possible way (swipe, cancel, success) quickly.
  5. Fix and prove: remove the dangling reference (weak instead of unowned, cancel observers in deinit or before dismissal), add a test or UI test for the dismissal path, and submit 5.2.1 with an expedited review request.
  6. After: a short write-up, a lint or code-review rule for unowned in delegates, and making the payment flow’s crash-free rate a release gate.
Exercisemedium

Turn a report into a test

The crash from the start of the lesson: CheckoutViewModel.total force-unwraps prices[$1.productID]!. You found that when a product is removed from the catalog, the cached cart still contains it. Write a fix and a test that would have caught it.

›

Decide what the user should see when a cart item has no price, then make the view model expose that instead of crashing.

SolutionTry it yourself first
struct CheckoutViewModel {
    var items: [CartItem]
    var prices: [Product.ID: Decimal]

    /// Items whose product is no longer sold; the screen asks the user to remove them.
    var unavailableItems: [CartItem] { items.filter { prices[$0.productID] == nil } }

    var total: Decimal {
        items.reduce(0) { sum, item in
            guard let price = prices[item.productID] else { return sum }   // excluded and shown separately
            return sum + price * Decimal(item.quantity)
        }
    }
}

@Test func removedProductDoesNotCrashAndIsReported() {
    let model = CheckoutViewModel(
        items: [CartItem(productID: 1, quantity: 2), CartItem(productID: 99, quantity: 1)],
        prices: [1: 10]
    )
    #expect(model.total == 20)
    #expect(model.unavailableItems.map(\.productID) == [99])
}

The fix handles the missing price on purpose: the total excludes it, and the screen can show “1 item is no longer available”. The test reproduces the exact state from the crash.

  • Sanitizers in CI: TSan (races), ASan/UBSan (unsafe memory, C deps), Zombies (ObjC over-release), Main Thread Checker, Core Data concurrency debug.
  • Production signal: crash reporter + os.Logger breadcrumbs and custom keys; MetricKit MXDiagnosticPayload (crashes, hangs, CPU, disk writes) and MXAppExitMetric exit reasons.
  • Triage by when (version, server, OS), who (devices, locales, states), what (breadcrumbs). Device-specific memory exits point to image or buffer sizes.
  • Concurrent queues need barriers for writes; corruption crashes appear far from the race.
  • Incidents: pause phased release, remote kill switch, regression test, expedited review; crash-free sessions as a release gate.

Check this part

  1. Which tool finds two threads writing the same variable at once?

  2. Why add Logger messages around important steps?

  3. Where do you see how often the app was killed for exceeding its memory limit?

  4. A new crash group grows fast during a phased release. First step?

For crashes you can't reproduce, run the Thread Sanitizer (data races), Address Sanitizer (memory errors), Zombies and the Main Thread Checker in tests and debug builds. Add breadcrumbs with os.Logger and a crash reporter, read MetricKit diagnostics for hangs, crashes and exit reasons, and correlate with versions, devices and features. Fix the cause, add a test, and keep a kill switch for risky features.

Key takeaways

  • A crash report tells you which version, what kind of crash and where; symbolicate it with the build’s dSYM.
  • EXC_BREAKPOINT is usually a Swift check failing; EXC_BAD_ACCESS is memory or threads.
  • Fix the cause, not the symptom: a bounds check that hides a bug isn’t a fix.
  • Use Thread Sanitizer and breadcrumbs for crashes you can’t reproduce.
  • Classify by exception type and termination reason; read several reports per group.
  • Not every termination is a crash: watch MetricKit exit reasons for memory and watchdog kills.
  • Make races and memory bugs deterministic with sanitizers in CI.
  • Treat crashes as incidents: stop the spread, find the cause, prove the fix with a test.

Finished this page?Nice work, this page is complete!

Mark it as done to track your progress. It's saved in this browser, no account needed.

Its cards are now in your Bites review ⚡
Esc

Type to search the whole site.