Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 46 ยท Testing and Shipping

Debugging Xcode Apps

Debug iOS and SwiftUI apps in Xcode: breakpoints, lldb, print and Logger, the view debugger, crash logs, symbolication and the runtime errors you will meet most.

Every app misbehaves sooner or later. A list shows the wrong row, a screen never loads, or the app disappears the moment a tester taps a button. Debugging is the skill of turning "it is broken" into "this line received this value". Xcode gives you a full toolbox for that, and learning which tool answers which question saves hours.

This lesson covers breakpoints and the lldb console, printing versus the Logger API, the view debugger, reading crash logs, symbolication, and the runtime errors that beginners hit most. Xcode and the simulator cannot run on this site, so the Xcode steps are described and the SwiftUI snippets are read-only. The two runnable examples are honest stand-ins: a tiny logger that mimics levels and privacy, and a symbolicator that turns raw addresses into function names.

Pick the tool for the question

Breakpoints Stop the app and inspect real values.
Logging Follow what happened over time.
View debugger See why a view sits where it does.
Crash logs Find what killed the app on someone else's phone.

Stop and look, or record and read. Most bugs need one of each.

1 / 2

Breakpoints

A breakpoint pauses the running app at a line. Click the gutter beside a line number in Xcode and a blue marker appears. Run the app (Cmd+R); when execution reaches that line it stops, and the debug area shows the call stack on the left, the variables in scope, and the lldb console.

Swift
// read-only: a breakpoint on the marked line shows `items` and `filter`
struct Inbox {
    var items: [String]

    func visible(matching filter: String) -> [String] {
        let result = items.filter { $0.contains(filter) }   // set a breakpoint here
        return result
    }
}

While stopped you have four stepping commands in the toolbar: continue (run to the next breakpoint), step over (run this line, stop at the next), step into (enter the function being called) and step out (finish the current function). Stepping over is the default habit; step into only when the callee is the suspect.

Breakpoints can be tuned by right-clicking them (or using the Edit Breakpoint popover):

  • Condition: stop only when an expression is true, such as filter.isEmpty. This beats pausing on every iteration of a loop.
  • Ignore count: skip the first N hits.
  • Action: run a debugger command or log a message, then optionally automatically continue. With "continue after evaluating actions" a breakpoint becomes a log line you never have to recompile.
  • Exception breakpoint: stops the moment a Swift error or Objective-C exception is thrown, so the call stack still shows the cause rather than the crash site. Add it from the Breakpoint navigator with the plus button.
  • Symbolic breakpoint: stops whenever a named function runs, even in code you do not own.

The lldb console

When stopped, the console at the bottom accepts lldb commands. The ones you will use all the time:

TEXT
(lldb) po items            // print a readable description of an object
(lldb) p filter            // print with type information
(lldb) frame variable      // list every local variable
(lldb) bt                  // backtrace: the call stack
(lldb) expression filter = "inbox"   // change a value while paused

Changing a value mid-run lets you test a fix before you edit code. Since Xcode shows a value in a hover tooltip as well, the console matters most for expressions, such as po items.map(\.count).

print is the quickest way to learn what a value was. It goes to the Xcode console and costs nothing to write, but it is unstructured, it ships in release builds, and you cannot filter it.

The unified logging system, used through the Logger type from the os module, fixes that:

Swift
// read-only: logging with categories, levels and privacy
import os

private let logger = Logger(subsystem: "com.example.Inbox", category: "network")

func loadMessages(for user: String) {
    logger.debug("Starting load")                       // developer detail
    logger.info("Loading for \(user, privacy: .private)")
    logger.error("Server answered \(404)")               // something went wrong
}

Three ideas matter here:

  1. Subsystem and category label every message, usually the bundle identifier and a feature name, so you can filter by them in Xcode's console search or in the Console app.
  2. Levels (debug, info, notice, error, fault) decide how the system keeps the message. Debug messages are cheap and are dropped unless something is collecting them.
  3. Privacy: string interpolations are redacted as <private> when the app is not attached to a debugger, unless you mark them .public. Dynamic strings default to private so you do not leak a user's email into a log a support engineer can read.

The stand-in below mimics those rules so you can see them. It is not the real os framework, only a model of a level filter plus redaction.

Swift A logger stand-in: levels and privacy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Leave useful Logger calls in the app instead of deleting your prints once the bug is fixed. A good log is a record you can read later without reproducing the problem.

The view debugger

Some bugs are about layout: a button that cannot be tapped, a view hidden under another, text cut off. Pause the app and choose Debug View Hierarchy (the stacked-rectangles button in the debug bar). Xcode freezes the screen and shows it as a 3D stack of layers you can rotate. Click a layer to see its frame, its modifiers and its place in the tree.

Typical findings: a transparent view covering a button (add allowsHitTesting(false) or remove it), a frame that is wider than the screen, or a Spacer pushing something off-screen. In SwiftUI you can also temporarily add a colored .border(.red) or .background(.yellow) to see where a view's bounds actually are. Remember that modifier order changes what the border wraps, as explained in View Modifiers and Their Order.

For why a view re-renders, SwiftUI offers Self._printChanges() inside body during development. It prints which property triggered the update. Remove it before you ship; Performance, Instruments and Smooth Scrolling covers measuring with the SwiftUI instrument instead.

Swift
// read-only: debug-only helper, never ship this
var body: some View {
    let _ = Self._printChanges()
    Text(model.title)
}

Reading a crash

A crash is the app being terminated, either by your code (a trap such as a force unwrap of nil) or by the system (a watchdog killing a slow launch, or the memory limit). When it happens under the debugger, Xcode stops on the offending line and prints a reason in the console. Read that reason first. It often says exactly what went wrong.

When it happens on a tester's device you work from a crash log. In Xcode, open Window > Organizer > Crashes to see reports collected from TestFlight and the App Store, grouped by cause and sorted by how many users hit them. A report has these parts:

  • Exception type and codes, such as EXC_BAD_ACCESS (touched memory it should not), EXC_BREAKPOINT (a Swift runtime trap like a failed force unwrap or array index) or EXC_CRASH with signal SIGABRT (the app aborted itself).
  • Termination reason, for example a watchdog timeout.
  • Crashed thread backtrace: the call stack at the moment of the crash, one frame per line, newest on top.
  • Binary images: the list of loaded libraries with their load addresses.

Read the crashed thread from the top and find the first frame that belongs to your app. Frames above it are system code reacting to your mistake; the app's frame is where to look.

Symbolication

A release build strips most names to keep the binary small, so a raw frame looks like 0x0000000104a3c1f4. Symbolication maps that address back to a function and line, using the dSYM file produced when you archived the build. Xcode keeps dSYMs with each archive, and when you upload to App Store Connect the dSYM goes along so the Organizer can symbolicate for you. If crashes show as bare addresses, the dSYM for that exact build is missing: always keep the archive of every build you ship.

The idea is simple arithmetic. The system loads your binary at some base address; each frame's address minus the base is an offset, and the dSYM says which function covers that offset. The stand-in below does the same with a small table.

Swift Symbolicating addresses by hand

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The last address is unknown because it falls outside every symbol. In a real crash log such a frame belongs to a system library, whose symbols Apple supplies.

Common runtime errors

A handful of problems account for most beginner crashes:

Message or symptom Usual cause Fix
Fatal error: Unexpectedly found nil while unwrapping an Optional value A force unwrap (!) on nil Use if let, guard let or a default value
Index out of range Reading array[i] past the end Check indices.contains(i) or use first/last
Thread 1: EXC_BAD_ACCESS Dangling memory, usually in unsafe or UIKit interop code Run with Address Sanitizer enabled in the scheme
Publishing changes from background threads is not allowed Updating observed state off the main actor Mark the type @MainActor or hop to it
A NavigationLink is presenting a value of type ... but there is no matching navigationDestination The destination for that type is missing Add navigationDestination(for:)
keyNotFound / typeMismatch decoding error JSON does not match the model Print the DecodingError and fix the model or CodingKeys
Preview crashes but the app runs Preview data missing or a dependency not injected Provide sample data and environment in the preview
Modifying state during view update Changing @State inside body Move the mutation into onAppear, task or an action

When a Swift error is thrown, always print the whole error, not just error.localizedDescription. A DecodingError carries a coding path that points to the exact key.

A good order for any bug: reproduce it, read the first message, put a breakpoint just before the failing line, check the actual values, then change one thing. Guessing and editing several things at once makes the bug harder to understand.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. You want to pause only when filter.isEmpty is true inside a loop that runs 10,000 times. What do you add?

    A breakpoint condition makes Xcode stop only when the expression is true, so you avoid pausing on every iteration.
  2. 2. Why does Logger show <private> for an interpolated string in a log collected from a user's device?

    The unified logging system redacts dynamic strings when no debugger is attached, so personal data does not leak into logs unless you opt in with privacy: .public.
  3. 3. A crash log shows only hex addresses instead of function names. What is most likely missing?

    Symbolication needs the debug symbols (dSYM) produced when the build was archived. Keep every shipped archive.
  4. 4. Which tool best explains why a button cannot be tapped because another view covers it?

    The view debugger shows the layered view hierarchy in 3D, so you can spot a transparent view on top.

Summary

  • Breakpoints stop the app so you can inspect values; use conditions, actions and exception breakpoints to cut noise.
  • lldb commands such as po, p, bt and expression inspect and even change state while paused.
  • Prefer Logger over print for lasting logs: subsystems, categories, levels and privacy redaction.
  • The view debugger and Self._printChanges() explain layout and re-render surprises.
  • Crash logs list the exception type and the crashed thread; read down to the first frame of your own code.
  • Symbolication needs the dSYM of the exact build; keep every archive you ship.

Next: Signing, TestFlight and App Store Release