Swift & iOS

Learn Xcode navigators, compiler errors, LLDB debugging, Instruments, CPU and GPU profiling, memory diagnostics, and practical investigation workflows.

~52 min reading~54 min practice estimate
Suggest content

Xcode Debugging & Profiling

🟪 Syntax · 🟦 Tools/APIs · 🟩 Correct pattern · 🟥 Bug · 🟨 Version or measurement caveat · 🧠 Explanation

Reviewed: 22 October 2026. This guide uses official Apple and Swift sources and independent practice questions. Tool names and available diagnostics vary by Xcode, OS, target, and hardware. Code and logs below are illustrative and uncompiled; numerical examples are synthetic. No real application or device was profiled for this lesson.

The useful workflow is: reproduce one symptom, choose a tool that can observe it, collect a narrow recording, explain the evidence, change one cause, and repeat the same scenario. A navigator screenshot identifies controls; it does not establish a performance problem.

Read the navigator bar correctly

In the supplied cropped reference, the visible controls run Bookmarks → Find → Issues → Tests → Debug (selected) → Breakpoints → Reports. The highlighted device-like symbol is the Debug navigator, based on its position between Tests and Breakpoints and Apple's navigator reference. It is not a dedicated GPU navigator. The crop contains no CPU/GPU measurements, memory values, frame times, running process, or verified Xcode version. Use the control's tooltip or View → Navigators in your installed Xcode to confirm its name. Apple navigator overview

NavigatorWhat it answersUseful next step
BookmarksWhere did I save a source location or note?Return to that context; bookmarks are not breakpoints or performance samples.
FindWhere is a symbol/string used across the workspace?Search call sites before changing an API or tracing a state write.
IssuesWhat diagnostics has Xcode reported?Select the diagnostic and read its related notes, not just the red underline.
TestsWhich tests can I run, and what is their status?Run the smallest reproduction, then inspect its result.
DebugWhat is the running/paused process doing?Inspect gauges while running; inspect threads and stacks while paused.
BreakpointsWhere and under what conditions should execution stop?Choose a source, conditional, symbolic, error, or exception breakpoint.
ReportsWhat happened during a particular build/test/run?Open the relevant invocation and expand the actual failing command/log.

Project, Source Control, and Symbol navigators may appear elsewhere in a wider bar. Icon positions and shortcuts can change or be customized; prefer named menus over memorizing one screenshot.

Choose the tool before recording

Symptom/toolWhere and howInterpret the evidenceNext action
Build failure / Issues + ReportsBuild the intended scheme/destination; open Issues, then the matching build report and failed command.Distinguish compiler, linker, script, signing, install, and launch stages. Later messages may be consequences.Fix the earliest causal diagnostic and rebuild the smallest affected target.
CPU or memory suspicion / Debug navigatorRun the scenario under the debugger; select its resource gauge/report.Gauges show a trend during that run. Aggregate CPU is not main-thread responsiveness; memory growth is not automatically a leak.Mark the interaction, then select an appropriate Instruments trace or memory graph.
Expensive CPU work / CPU Profiler or Time ProfilerProduct → Profile; choose the device/app and available template; record a short repeatable interaction.CPU Profiler weights sampled stacks by CPU cycles on supported hardware; Time Profiler samples running stacks over time. Inspect the relevant interval and thread.Find costly callers/self work, reduce work, and repeat under matching conditions.
Hang or scrolling hitch / Hangs, Animation Hitches, SwiftUI, System TraceAdd the matching Instruments tracks; reproduce the stall and zoom to its interval.Separate a busy main thread, a blocked thread, actor/executor contention, and rendering delays.Inspect the dependency or stage responsible instead of moving arbitrary work to another queue.
Unexpected object lifetime / Memory GraphReach the lifecycle boundary; click Debug Memory Graph in the debug bar. Inspect surviving instances and incoming references.A graph is a snapshot. An object may be legitimately cached, abandoned, or part of a cycle.Find the retaining owner and repair its lifecycle contract.
Growing allocations / Allocations + LeaksProfile repeated feature cycles; mark allocation generations around them.Allocations reveals lifetime/churn; Leaks finds supported leak patterns. Neither alone explains every retained object.Bound caches, release owners, or reduce transient allocation peaks; confirm repeated-cycle behavior.
Visual artifact / Metal captureEnable GPU Frame Capture in the Run scheme options; run, capture the affected scope, inspect the Metal debugger.Inspect commands, passes, attachments, resources, shaders, and available counters for captured work.Fix incorrect resources or expensive passes; recapture on supported target hardware.
GPU/CPU scheduling over time / Metal System TraceProduct → Profile; select/add Metal System Trace where supported; capture several affected frames.Correlate CPU submission, GPU execution, idle gaps, and frame pacing across time.Investigate the limiting stage; one frame capture cannot explain every intermittent stall.
Battery or thermal complaint / Power ProfilerOn supported devices, add Power Profiler in Instruments; record representative foreground/background behavior.Correlate CPU, GPU, network, display, charging, and thermal context.Reduce repeated work/wakeups and compare multiple traces on the same device model.

Apple recommends CPU Profiler for CPU optimization where supported because cycle weighting avoids time sampling's bias across cores/frequencies. Time Profiler remains useful and broadly available; neither provides an exact invocation count from sample counts. CPU profiling, sampling versus execution frequency

A repeatable debugging and profiling workflow

  1. Write the reproduction. Record commit/build, input size, account state, scheme, target, destination, OS, device, compiler/language mode, and isolation settings. Name the expected and actual result. Keep private data out of shared logs.
  2. Classify the failure. A compiler diagnostic prevents compilation; a linker error prevents assembling the executable; signing/install errors concern deployment. A runtime crash stops execution. A logical bug produces a wrong result without necessarily crashing. A performance regression requires comparable measurements.
  3. Capture evidence at the right boundary. Keep the original build/crash report. Use a small deterministic test for correctness; use a realistic device scenario for performance. Add a signpost interval around a meaningful operation when correlation is difficult.
  4. Change one cause and retest. Avoid deleting caches or disabling safety checks as the first response to an unexplained error. Preserve the failing log before trying an environment repair. A clean build can distinguish an incremental artifact problem; it cannot repair a missing protocol requirement.
  5. Verify both correctness and cost. Use a release-like optimized build for representative performance, with matching symbols. Keep an unsanitized baseline and separate diagnostic runs. Compare repeated runs, distributions, and user-visible outcomes, not just the best result.

CPU and responsiveness: use the gauge to find when activity changes, then profile that interval. Filter the call tree by the relevant thread, inspect inclusive versus self cost, and check callers before blaming a leaf function. Read the tool’s CPU-percentage definition: core normalization and denominators differ, so do not assume 100% means the entire device’s maximum capacity. Low CPU does not exclude a hang: the main thread may be waiting on a lock, file I/O, or work that cannot progress. Hangs concern delayed responsiveness; hitches concern missing rendering deadlines. Avoid declaring every frame has a universal 16.7 ms budget; refresh rates and pipeline stages differ. Apple responsiveness guide, hangs and hitches

Memory: repeat present → use → dismiss, wait for intended asynchronous cleanup, then inspect surviving owners. Use Allocations generations to distinguish persistent growth from temporary peaks. Memory Graph shows references; allocation stack logging can connect an allocation to its origin, with overhead. Leaks is not proof that all unnecessary retained memory is absent. Simulator's green gauge is not a device memory-budget guarantee. Memory evidence and tools

GPU: first determine whether the symptom involves UI updates, composition, CPU submission, or GPU execution. For ordinary UIKit/SwiftUI animation, start with Animation Hitches/SwiftUI/Core Animation evidence; use Metal tooling when it can expose the relevant rendering workload. An unavailable or blank GPU gauge is missing evidence, not zero utilization. Low FPS or jank alone does not identify whether CPU, GPU, allocation pressure, or another stage is limiting progress. GPU capture, replay, counters, and shader profiling depend on the target, GPU family, OS, Xcode, and capture settings. Simulator uses the host GPU and cannot represent an iPhone GPU's timing or capabilities. Metal capture, GPU analysis, Simulator limitations

Power: Power Profiler is documented for iPhone with iOS 26+ and iPad with iPadOS 26+. Its overall system-power reading is zero while charging; paired debugging also affects sleep behavior. Record charging, brightness, connectivity, thermal state, and background activity. Compare the same device model and scenario; an energy-impact score is not a universal battery percentage or proof that one function caused the drain. Power Profiler setup and interpretation

Compiler, debugger, and diagnostic essentials

For build failures, expand the first causal diagnostic in the failing command, including notes. Parallel logs do not always list the root cause first globally. Confirm file/target membership, package product links, deployment target, SDK, architecture, generated outputs, and build configuration as relevant. For signing, check the intended team, bundle ID, capabilities, signing mode, and destination; do not randomly replace certificates or entitlements.

If a compiler crashes with an internal compiler error or stack dump, preserve the exact toolchain, invocation, configuration, first causal diagnostic, and crash output. Reduce the source without changing the failure; compare a supported known version when practical. Distinguish an editor/indexing problem from a reproducible build failure. Sanitize the minimal reproducer and report it through Apple's or Swift's appropriate issue channel. A diagnostic rejecting invalid code is not itself a compiler defect. Do not default to deleting Derived Data or disabling concurrency checks.

Breakpoints and stepping in practice

Stop mechanismUse it forCheck before interpreting it
Source/linePause near a known state transition.The line must map to executable code in the binary being debugged.
SymbolicStop in a named function, including framework code.The module/symbol must load and resolve; spelling or optimization can affect resolution.
Swift ErrorInspect where a Swift error is thrown.Handled errors may also hit; a stop does not prove an eventual crash.
Objective-C ExceptionInspect exceptions from Objective-C code/frameworks.Swift do/catch does not generally recover Objective-C exceptions.
WatchpointStop when valid storage is written/read.Storage lifetime, optimized variables, and hardware slots limit coverage.

Click the source gutter to add a line breakpoint, then Control-click → Edit Breakpoint. A condition such as index == 8 stops for a relevant local state. Ignore 8 times skips the first eight encounters; hit count is a debugger encounter count, not a production business metric. Do not confuse condition with ignore count, or mutate program state in a condition.

Add a Log Message or Debugger Command action, such as frame variable index. Select Automatically continue after evaluating actions to collect observations without a manual stop. This still enters debugger machinery and can perturb a race; it is not zero-overhead telemetry. Keep actions limited to needed, nonsecret data.

For UIKit constraint conflicts, add a symbolic breakpoint named UIViewAlertForUnsatisfiableConstraints through the Breakpoint navigator's Add menu. Inspect the conflicting constraints and their creation path. A visually acceptable fallback does not make the conflict harmless. Apple breakpoint setup/actions, Auto Layout conflicts

Name recurring breakpoints, filter/group them by source file or issue using the navigator's available controls, and disable rather than delete a temporarily irrelevant set. Check both individual enabled state and global activation. Share project/workspace breakpoints deliberately when useful; avoid personal paths, sensitive actions, and noisy diagnostic sets. An unresolved location differs from a resolved breakpoint with zero hits: verify loaded modules, correct process/build, source mapping, optimization, and whether the path was reached. Managing and sharing breakpoints

Pause and choose the correct thread → stack frame before inspecting locals. A frame is one active call's context. A dispatch queue schedules work; it is not necessarily a permanent thread. Step Over executes the call without descending, Step Into enters it when debug information permits, and Step Out continues until the current frame returns. In optimized builds, inlining, removed locals, and reordered instructions can make source stepping surprising. Use a suitable debug reproduction for inspection and preserve optimized builds for representative performance. Pausing changes scheduling, so a race disappearing under the debugger is not proof of a fix. Apple stepping guide, threads and frames

In LLDB, start with inspection: thread backtrace, thread backtrace all, and frame variable. po/expression can execute code, change state, block, or fail when optimization removes values. Match crash reports to their build and dSYM before interpreting symbolicated stacks. A stopped frame identifies a symptom location; inspect callers and prior state before concluding it is the origin.

KeywordWorking meaning
Scheme / target / destinationActions and settings / product to build / device or Simulator to run on.
Diagnostic / note / Fix-ItCompiler finding / context explaining it / suggested edit requiring review.
Inclusive / self costWork attributed to a function and descendants / work within the function itself.
CPU time / wall timeProcessor execution / total elapsed time, including waits.
Sample / invocationPeriodic observation / actual call; these counts are not interchangeable.
Footprint / allocation / retentionMemory impact / reserving memory / keeping ownership alive.
Symbolication / dSYMTranslating addresses into symbols / matching debug symbols for a build.
Signpost / baseline / regressionNamed timing event/interval / comparable reference / worse measured behavior.

Enable runtime tools in Edit Scheme → Run or Test → Diagnostics, or a test-plan configuration where available. Address Sanitizer helps identify unsafe memory access, Thread Sanitizer detects exercised data races, and Main Thread Checker checks supported main-thread-only API usage. UBSan supports C-based languages, not Swift generally. Support and combinations depend on destination; a disabled option is not a license to assume coverage. Sanitizers, Zombies, stack logging, debugger attachment, and GPU capture can alter timing/memory. Diagnostic runs and clean performance measurements serve different purposes. Apple runtime diagnostics

Xcode practice questions

These 18 questions are independent study prompts. Discuss the evidence, tool choice, correction, and verification before opening the answers. Suggested practice: 5–10 minutes each; this is a study suggestion, not a measured duration or official assessment format.

XCODE-01 — Can a selected Xcode navigator icon prove a memory problem?

A cropped navigator bar has Debug selected but shows no resource readings. A teammate calls it GPU usage and concludes that the app uses too much memory.

Optional follow-up questions
  • Describe where to inspect current CPU and memory activity.
  • Identify where a past failing build and its full log are recorded.

XCODE-02 — Which build message identifies the actual source error?

The synthetic build log contains both a failed command and a diagnostic about the source declaration. Identify the declaration that needs correcting.

TEXT
CompileSwiftSources normal arm64
Profile.swift:14:28: error: 'nil' cannot initialize specified type 'String'
    var nickname: String = nil
Command SwiftCompile failed with a nonzero exit code
Optional follow-up questions
  • Explain how Issues and Reports supply complementary context.
  • Preserve the intended meaning of an absent nickname.

XCODE-03 — How do you narrow down a SwiftUI expression that cannot be type-checked?

A large SwiftUI body combines nested ForEach calls, overloaded initializers, and optional values, then produces the diagnostic below.

TEXT
error: the compiler is unable to type-check this expression in reasonable time;
try breaking up the expression into distinct sub-expressions
Optional follow-up questions
  • Explain what a typed child view improves.
  • Define what evidence is needed before reporting a minimal compiler defect.

XCODE-04 — Why can linking fail after source compilation succeeds?

The synthetic log reports a link failure after compilation. Determine which module or binary should supply the missing implementation.

TEXT
Ld App normal arm64
Undefined symbols for architecture arm64:
  "PaymentsClient.submit()", referenced from CheckoutModel.o
clang: error: linker command failed with exit code 1
Optional follow-up questions
  • Check target membership, linked products, and platform-compatible slices.
  • Distinguish a missing symbol from a device binary linked into a Simulator build.

XCODE-05 — What should you check when a physical-device build fails signing?

The Simulator build runs, but the physical-device destination reports the synthetic signing failure below.

TEXT
Signing for "App" requires a development team.
No profiles for 'com.example.app' were found.
Optional follow-up questions
  • Record the active scheme, destination, and nonsecret settings before changes.
  • Explain how the profile, entitlements, and device eligibility must agree.

XCODE-06 — Why can this synchronous caller not access MainActor-isolated behavior?

Assume Swift 6 language mode and a nonisolated synchronous caller. The diagnostic reports access to MainActor-isolated behavior.

SWIFT
@MainActor
final class ScreenModel {
    var title = ""
    func updateTitle(_ title: String) { self.title = title }
}
​
nonisolated func receive(_ title: String, model: ScreenModel) {
    model.updateTitle(title)
}
Optional follow-up questions
  • Explain when an explicitly owned asynchronous handoff is appropriate.
  • Record compiler, language, isolation, SDK, and relevant feature settings.

XCODE-07 — Which breakpoint finds where a Swift error was originally thrown?

This illustrative call fails at try!. Choose a breakpoint that reveals the earlier throw site rather than only the final trap.

SWIFT
enum LoadError: Error { case missingRecord }
​
func loadRecord() throws -> String {
    throw LoadError.missingRecord
}
​
let record = try! loadRecord()
Optional follow-up questions
  • Contrast Swift errors with Objective-C exceptions and array-bounds traps.
  • Explain why blanket optional-try recovery can hide useful failure information.

XCODE-08 — How can you locate the code that unexpectedly changes a value?

A model's selectedIndex changes unexpectedly after dismissal. Use the selected frame and the diagnostic commands below to investigate the writer.

TEXT
(lldb) thread backtrace all
(lldb) frame variable selectedIndex
(lldb) watchpoint set variable selectedIndex
Optional follow-up questions
  • Compare conditional breakpoints, logging actions, ignore counts, and watchpoints.
  • Check unresolved symbols and distinguish stepping over, into, and out of a call.

XCODE-09 — Why can a stale search result pass Thread Sanitizer checks?

Two requests start in order, but the second completes first. Assume the repository is Sendable and the model is MainActor-isolated.

SWIFT
@MainActor
func reload(_ query: String) async throws {
    visibleRows = try await repository.search(query)
}
Optional follow-up questions
  • Describe a test that completes the newer request before the older one.
  • Explain what a clean sanitizer run cannot prove.

XCODE-10 — What does a CPU profiler's sampled call tree actually measure?

The synthetic readings below suggest CPU activity during decoding. Interpret them without treating the number of samples as an invocation count.

TEXT
Scenario: open photo grid
CPU gauge: sustained high activity
Selected interval: 2 seconds
Time Profiler: decode -> 600 samples including descendants
Optional follow-up questions
  • Distinguish self cost from inclusive cost.
  • Identify the workload, build, device, interval, and sampling context needed for a fair comparison.

XCODE-11 — Why can creating a Task still leave the UI unresponsive?

This MainActor method creates a task that performs expensive synchronous decoding. The app still hitches during the operation.

SWIFT
@MainActor
func loadPreview() {
    Task {
        preview = expensiveSynchronousDecode(bytes)
    }
}
Optional follow-up questions
  • Include cancellation and request-freshness checks before publication.
  • Choose measurements that distinguish actor contention from GPU-bound rendering.

XCODE-12 — How can an app's UI hang while CPU usage is low?

A synthetic main-thread stack shows a semaphore wait. Determine what must happen elsewhere before that wait can finish.

TEXT
Thread 1 (main): waiting
  semaphore_wait_trap
  LegacyLoader.loadSynchronously()
  CheckoutViewModel.refresh()
Optional follow-up questions
  • Explain why optimizing unrelated parsing cannot repair a wait cycle.
  • Choose a trace and reproduction that expose the dependency order.

XCODE-13 — How do you find what keeps a dismissed object alive?

Repeatedly presenting and dismissing an editor leaves editor models alive. Review the callback ownership in this example and plan a memory-graph investigation.

SWIFT
final class EditorModel {
    var title = "Draft"
    var onSave: (() -> Void)?
​
    func configure() {
        onSave = { print(self.title) }
    }
}
Optional follow-up questions
  • Compare a retained callback with a deliberately bounded cache.
  • Verify that the intended object lifetime changes after the repair.

XCODE-14 — Does increasing memory always indicate a strong reference cycle?

A photo grid's memory grows during scrolling and only partly falls after dismissal. Decide what evidence would distinguish temporary work from persistent retention.

Optional follow-up questions
  • Compare allocation generations, retained owners, and cache policy.
  • Measure representative device peaks and steady-state behavior before setting a budget.

XCODE-15 — When is a GPU frame capture more useful than a timeline trace?

A scrolling screen stutters intermittently, but one captured frame looks correct. Choose evidence that can separate UI work, command submission, and GPU execution.

Optional follow-up questions
  • Explain what a detailed Metal capture adds after locating an affected interval.
  • Reproduce on supported, representative physical hardware.

XCODE-16 — Can measurements from different configurations prove a performance improvement?

The synthetic comparison reports a 40 percent improvement, but its before and after measurements use different conditions.

TEXT
Before: Debug + debugger + Thread Sanitizer, Simulator, 1 run = 100 ms
After:  Release, physical phone, warm cache, 1 run = 60 ms
Claim: 40% faster in production
Optional follow-up questions
  • Identify the confounding conditions and a consistent warm-up policy.
  • Explain how signposts and repeatable performance tests help establish a fair baseline.

XCODE-17 — Which diagnostic helps locate a read after memory has been deallocated?

Review this intentionally invalid pointer example without executing it in a production process. Identify the diagnostic suited to its resource-lifetime error.

SWIFT
let pointer = UnsafeMutablePointer<Int>.allocate(capacity: 1)
pointer.initialize(to: 42)
pointer.deinitialize(count: 1)
pointer.deallocate()
print(pointer.pointee)
Optional follow-up questions
  • Contrast Address Sanitizer, Thread Sanitizer, and Main Thread Checker.
  • Explain destination support, instrumentation overhead, and the limits of a clean run.

XCODE-18 — How do you investigate background battery drain without guessing its cause?

A user reports battery drain after periodic synchronization is enabled. Plan evidence collection that avoids exposing private user data.

Optional follow-up questions
  • Distinguish frequent wakeups from CPU-heavy processing and rendering work.
  • Define a success criterion that preserves required synchronization behavior.

Xcode questionnaire answers

The answers are discussion rubrics, not a single approved architecture. A strong response ties a finding to evidence, makes ownership explicit, and states what remains unverified.

XCODE-01 — Answer

Short answer: The selected icon identifies the Debug navigator, not a GPU-only mode or a measurement of excessive memory. Inspect the running app's actual resource reports during a reproduction before drawing a resource conclusion. Historical build failures belong in the recorded build reports rather than being inferred from the selected icon.

Detailed explanation:

Illustrative tool-discovery commands list the installed Instruments templates and destinations; they do not record CPU/GPU or memory usage.

BASH
xcrun xctrace list templates
xcrun xctrace list devices

Select a supported template/device after identifying the symptom; the current process's Debug navigator readings remain a separate source of evidence.

The selected control is Debug navigator; it provides process debugging information, not a GPU-only mode. The crop contains no resource readings, so it cannot support the memory claim. Run the correct scheme/destination, open Debug, choose the app's CPU or memory report, and reproduce the interaction. Use a matching Instruments recording for attribution or Memory Graph for surviving owners. Open Reports for the historical failing build and its detailed log. Check tooltips/named menus when identifying a control on a different Xcode version; a familiar icon is not a measurement.

XCODE-02 — Answer

Short answer: Start with the specific source diagnostic rather than the wrapper command's final failure message. Here a nonoptional string is being initialized with no value, so decide whether the model truly allows absence and correct its declaration accordingly. Deleting build caches cannot fix that type mismatch.

Detailed explanation:

Illustrative corrected model when an absent nickname is valid; give the UI an explicit display fallback without discarding the underlying optionality.

SWIFT
struct Profile {
    var nickname: String? = nil
    var displayName: String { nickname ?? "Guest" }
}
var profile = Profile()
assert(profile.displayName == "Guest")
profile.nickname = "Alex"
assert(profile.displayName == "Alex")

The source declaration tries to initialize a nonoptional String with nil. If absence is a real domain state, use var nickname: String? = nil; otherwise choose a valid initial string. The command's nonzero exit is a consequence. Issues supplies navigable diagnostics and notes; Reports preserves the particular command, configuration, and surrounding output. Verify the intended target and fix this semantic error before treating it as stale build state. Rebuilding confirms that the cascade disappears. Cache deletion cannot change the type relationship and can erase useful context without answering the cause.

XCODE-03 — Answer

Short answer: Reduce the expression in meaningful pieces until the compiler can point closer to the mismatch. Give ambiguous intermediate values explicit types and check optionals, initializer labels, collection elements, and row identifiers. Extracting a small typed view can clarify the contract; type erasure alone does not repair invalid data flow.

Detailed explanation:

Illustrative typed extraction narrows the compiler's work and makes an optional price branch explicit. Product supplies name: String and priceLabel: String?.

SWIFT
struct ProductRow: View {
    let product: Product
    var body: some View {
        HStack {
            Text(product.name)
            if let price = product.priceLabel {
                Text(price)
            }
        }
    }
}

Place the row behind the original stable product ID; extraction is not permission to change list identity or behavior.

Reduce the body in meaningful sections, giving intermediate values and closure parameters explicit types where ambiguity exists. Check collection element types, optional unwrapping, initializer labels, and each ForEach ID. Extract a typed child view or helper so the compiler reports an error closer to the actual mismatch. Preserve behavior while reducing the expression; do not rewrite the entire screen blindly. Type erasure may hide inference pressure but does not correct invalid data flow and can obscure identity/performance tradeoffs. If a minimal valid reproduction still fails, record the toolchain, settings, source, and diagnostic for a compiler report.

XCODE-04 — Answer

Short answer: Compilation can accept a reference to an implementation that is missing when the final executable is linked. Inspect the exact missing symbol and the dependency that should provide it, including target membership and linked products. A device-versus-Simulator binary mismatch is a different compatibility problem and needs the correct platform build.

Detailed explanation:

Illustrative read-only settings comparison for a scheme named App; save the actual failed link invocation separately because settings alone do not prove a symbol was linked.

BASH
xcodebuild -showBuildSettings -scheme App -configuration Debug -destination 'generic/platform=iOS'
xcodebuild -showBuildSettings -scheme App -configuration Debug -destination 'generic/platform=iOS Simulator'

Compare platform/product/search-path settings and linked package products. These commands are examples, not build/link results from this lesson.

Compilation can produce a reference to a declaration whose implementation is absent from the final link. Inspect the failing link invocation and exact symbol, then locate the owning package/framework/object and whether the intended product is linked to the correct target. Check implementation membership and matching build configuration. A platform-slice mismatch is different: arm64 alone does not distinguish an iOS-device binary from an arm64 Simulator binary. Use the correct compatible package/XCFramework slice rather than editing a valid call or excluding architectures indiscriminately. Rebuild that destination and preserve the repaired dependency relationship in project configuration.

XCODE-05 — Answer

Short answer: Check the signing configuration for the intended target and device, including the team, bundle identifier, capabilities, signing mode, and applicable profile. A Simulator build does not prove those device settings are valid. Preserve the relevant nonsecret log and use the team's authorized signing workflow instead of exchanging private signing keys.

Detailed explanation:

Illustrative settings worksheet for the intended physical-device target, not an importable profile or a set of credentials.

TEXT
Scheme / target: the product that fails to install
Destination: intended eligible physical iPhone
Development team: the team's authorized Apple developer account
Bundle identifier: the registered product identifier
Signing mode: agreed automatic or managed manual workflow
Capabilities / entitlements: match product and provisioning profile
Preserve: failing signing log and nonsecret configuration
Never collect: another developer's private signing key

The messages concern signing configuration for that product/destination. Confirm the active scheme and target, selected development team, unique intended bundle ID, automatic/manual signing policy, required capabilities/entitlements, and a suitable profile/device registration where needed. Simulator success does not prove device signing is configured. Keep the log and relevant nonsecret settings before changes; avoid replacing identifiers or deleting certificates as a generic fix. Use the team's authorized account/signing workflow instead of transferring someone else's private key. Rebuild and install on the intended device, then verify that capabilities still match the product requirements.

XCODE-06 — Answer

Short answer: The caller is outside MainActor isolation and cannot synchronously assume it may perform that actor's work. When the contract allows it, make the call chain asynchronous and await the isolation boundary. Removing compiler checks or starting unowned fire-and-forget work changes safety or timing rather than automatically fixing the design.

Detailed explanation:

The synchronous caller cannot directly access MainActor-isolated behavior. Prefer making the caller async and awaiting the explicit boundary:

SWIFT
nonisolated func receive(_ title: String, model: ScreenModel) async {
    await model.updateTitle(title)
}

A synchronous callback may instead hand off to an explicitly owned MainActor task when its timing, ordering, cancellation, and lifetime contract permits it. Do not silently turn a synchronous guarantee into fire-and-forget work. Record Swift compiler version, language mode, strict concurrency, default actor isolation, relevant upcoming features, and SDK. Unsafe annotations can remove checks while leaving unsafe ownership intact. Swift data-race safety

XCODE-07 — Answer

Short answer: A Swift Error breakpoint can stop at the throw site before a forced try turns the error into a runtime failure. It can also stop for errors that are later handled, so a breakpoint hit is not itself proof of a crash. Inspect the error and call stack before choosing explicit recovery or propagation.

Detailed explanation:

Illustrative explicit recovery preserves the difference between a missing record and an unexpected load failure; loadRecord and LoadError are from the exercise.

SWIFT
enum RecordState {
    case content(String), missing, failed
}
func loadRecordState() -> RecordState {
    do {
        return .content(try loadRecord())
    } catch LoadError.missingRecord {
        return .missing
    } catch {
        return .failed
    }
}

The unexpected branch should feed an appropriate observable error/reporting boundary rather than silently claiming success.

A Swift Error breakpoint stops on the thrown Swift error and reveals its original context, before try! traps. It may also hit handled errors, so a hit alone is not a crash. An Objective-C Exception breakpoint targets Objective-C exceptions, including those raised through imported frameworks. An array bounds failure is a runtime trap and is not an ordinary thrown Swift error. Inspect the error value, inputs, callers, and the contract that made the operation supposedly infallible. Replace try! with explicit propagation or recovery appropriate to the domain. Blanket try? discards failure information and may make the UI silently wrong. Test the missing-record outcome and expected success separately.

XCODE-08 — Answer

Short answer: Stop or log at the relevant mutation boundary, using a condition to narrow the state you care about. A watchpoint can identify writes to supported, valid storage, while a symbolic breakpoint can target a known mutation method. Preserve the writer's call stack and remember that expression evaluation or debugger pauses can change program behavior.

Detailed explanation:

Illustrative LLDB experiments; replace the source/line and breakpoint ID with the actual resolved location. These are separate tests, so first disable/reset the other condition when comparing outcomes.

TEXT
breakpoint set --file EditorModel.swift --line 42
breakpoint modify --condition 'selectedIndex == 8' 1
thread backtrace all
frame variable selectedIndex
breakpoint modify --condition '' --ignore-count 8 1

The example assumes the new breakpoint receives ID 1; use LLDB's returned ID. An ignore count changes encounters, not the stored selectedIndex value.

Use a condition for a state predicate and ignore count for skipped encounters. A symbolic breakpoint targets a known mutation API; an automatically continuing action logs without manual stops. Watchpoints require valid storage and hardware support. The commands inspect all stacks, inspect a frame variable, and request a write watchpoint. Unresolved locations require symbol/process/build checks; zero hits on resolved locations suggests an unexecuted path or condition/activation issue. Select caller/callee frames deliberately: step over the call, into its implementation, or out to its caller. Optimized locals may be unavailable, and po can execute code. Preserve the writer’s stack; timing changes under a debugger do not prove race freedom.

XCODE-09 — Answer

Short answer: Thread Sanitizer looks for exercised unsafe memory accesses, not whether the newest user request wins. Actor-isolated requests can finish out of order without a data race, letting an older result overwrite newer state. Give requests an identity and test publication with deliberately controlled completion order rather than timing sleeps.

Detailed explanation:

Illustrative replacement inside a MainActor model with owner-controlled generation; the check and assignment share one uninterrupted actor segment.

SWIFT
func reload(_ query: String) async throws {
    generation += 1
    let requestGeneration = generation
    let rows = try await repository.search(query)
    try Task.checkCancellation()
    guard requestGeneration == generation else { return }
    visibleRows = rows
}

Invalidate the generation on the applicable account/lifecycle transition, even if no replacement request starts.

MainActor serializes each state access, but suspension permits A and B to complete in a different order. This is a logical freshness race, not necessarily a data race. A fake repository should hold each request's completion/continuation: start A, start B, complete B, then A, and assert B remains visible. Give each operation a unique generation and publish only when it still matches the current request, without another suspension between guard and assignment. Also check cancellation before publication. An exercised sanitizer detects particular memory-access bugs; it cannot establish the intended product ordering or cover unexecuted schedules.

XCODE-10 — Answer

Short answer: A sampled call tree records observations of running stacks, not an exact count of function calls. Select the affected time interval, inspect the relevant thread and callers, and distinguish a function's own work from work in its descendants. Compare representative runs before attributing the resource cost to one operation.

Detailed explanation:

Illustrative profile-analysis worksheet, not an actual Instruments export or measured result. It separates sample attribution from the operation whose cost matters.

YAML
journey: open_photo_grid
select_interval: only_the_affected_opening_operation
build: optimized_with_matching_symbols
inspect: [critical_thread, self_cost, inclusive_cost, callers]
sample_count_interpretation: observations_of_stacks_not_method_invocations
cycle_weighting: use_supported_CPU_Profiler_to_compare_CPU_resource_cost
verify: repeat_same_decode_workload_and_check_image_correctness

The gauge suggests activity during one run, not a root cause. Inspect a narrowly selected interval, relevant thread, call-tree attribution, optimization/symbol settings, input workload, and surrounding system state. Six hundred samples are observations of running stacks, not 600 invocations or an exact per-call duration. High inclusive cost may originate in descendants; high self cost suggests work in that function. Inspect callers before removing required decoding. CPU Profiler's cycle weighting is useful for identifying CPU resource consumers across asymmetric cores/frequency changes. Validate reduced cost and unchanged image quality with repeated representative runs, not a screenshot of the gauge.

XCODE-11 — Answer

Short answer: A task created in a MainActor context can inherit that isolation, so its synchronous CPU work may still occupy UI execution. Task syntax alone does not move that processing elsewhere. Put necessary heavy work behind a safe explicit execution boundary, then publish an accepted current result back to the UI owner.

Detailed explanation:

Illustrative Swift 6.2+ CPU boundary: immutable Sendable input/output and an explicitly supplied decoder implementation avoid shared UI-owned buffers.

SWIFT
struct PreviewSnapshot: Sendable {
    let width: Int
    let height: Int
    let rgba: [UInt8]
}
@concurrent
func preparePreview(
    bytes: [UInt8],
    decode: @Sendable ([UInt8]) throws -> PreviewSnapshot
) async throws -> PreviewSnapshot {
    try Task.checkCancellation()
    let value = try decode(bytes)
    try Task.checkCancellation()
    return value
}

The MainActor owner awaits this helper and applies the request-generation guard before assigning the result. CPU scheduling alone does not make an arbitrary decoder cooperatively cancellable inside its synchronous call.

The task created in this MainActor context inherits that isolation. Its synchronous decode can monopolize UI execution even though the syntax is asynchronous. First reduce unnecessary work; put necessary CPU processing behind an explicit safe execution boundary, for example a Swift 6.2+ @concurrent async helper receiving a Sendable byte snapshot and returning a safe result. Publish on MainActor after cancellation and generation checks. State the actual compiler/isolation settings. Profile Hangs/SwiftUI and available executor/thread tracks to detect MainActor contention; use rendering/GPU evidence before blaming GPU saturation. Moving work should not introduce unsafe shared image buffers or unbounded parallel decoding.

XCODE-12 — Answer

Short answer: The main thread may be blocked waiting rather than busy computing. Inspect the other threads or tasks and the dependency expected to release that wait; a single stack cannot distinguish slow I/O, contention, and a deadlock. Prefer an asynchronous call chain when a synchronous bridge would block the executor needed to finish the work.

Detailed explanation:

Illustrative async ownership boundary eliminates a synchronous semaphore bridge; app-specific loader/result types remain behind the ViewModel.

SWIFT
@MainActor
func refresh() async throws {
    let snapshot = try await loader.load()
    try Task.checkCancellation()
    state = .content(snapshot)
}

The caller owns/awaits the task and handles errors; add freshness guards when overlapping refreshes or session changes are allowed.

The main thread is waiting rather than consuming CPU. Inspect all thread/task stacks and the dependency expected to signal the semaphore. It may be slow I/O, contention, or a wait cycle; the fragment alone does not prove deadlock. A synchronous bridge can block the actor/executor or thread needed by the asynchronous completion. Make the operation async through the owning call chain so waiting suspends the task rather than blocking progress. Use System Trace or hang analysis to inspect scheduling/waits, and retain a reproduction that exercises the dependency order. Parsing optimizations cannot resolve a wait cycle unrelated to parsing.

🟦 Paused-target inspection — LLDB commands, not a captured diagnosis:

TEXT
thread list
thread backtrace all

In Xcode's Debug navigator, select the relevant thread and an application frame from those results, then inspect available locals without evaluating application expressions:

TEXT
frame variable

Optimized builds can omit variables. Suspended Swift tasks may not appear as complete logical call chains in thread backtraces; also inspect Xcode's task view and Swift Concurrency instrument where available. These commands inspect a paused process; a stack containing a wait is evidence to investigate, not proof of a closed cycle. LLDB thread and frame inspection

🧠 Synthetic wait-graph worksheet — not measured application output:

TEXT
main thread: holds main execution -> waits for semaphore S
completion: needs main execution -> would signal semaphore S
cycle: main -> S -> completion -> main

For each arrow, find its call site and owner in the reproduction. If the completion actually runs on an independent executor, this particular cycle is absent: investigate I/O, contention, a lost completion, or another dependency. Keep resource ownership separate from thread names; a serial queue is not a permanent thread. Repeat the corrected flow with controlled completion ordering and verify both UI responsiveness and result delivery, including cancellation/error paths. Do not use arbitrary sleeps as proof. The deadlock catalog supplies broken/corrected code for each major mobile family.

XCODE-13 — Answer

Short answer: Inspect the object in a memory graph after its expected cleanup and follow its strong incoming ownership links. A stored callback that captures its owner can form a reference cycle, but surviving objects may also belong to an intentional cache or another lifecycle. Repair the specific ownership contract instead of making every reference weak.

Detailed explanation:

The ARC explanation and worked examples explain why a strong owner keeps an instance alive and why a cycle can survive after dismissal.

Illustrative correction when the callback should become inert after the editor is released; the stored closure no longer strongly owns its model.

SWIFT
final class EditorModel {
    var title = "Draft"
    var onSave: (() -> Void)?
    func configure() {
        onSave = { [weak self] in
            guard let self else { return }
            print(self.title)
        }
    }
}

If saving must outlive the editor, give that work a separate explicit owner instead of relying on the callback to retain the whole screen.

The model owns onSave, whose escaping closure strongly captures the model: model → closure → model. Capture a memory graph after expected dismissal/cleanup, find EditorModel survivors, and inspect strong incoming edges to confirm this rather than assuming every survivor has that cause. A weak capture may be right if callbacks should become inert after owner release; clearing a one-shot callback or explicit teardown may better express ownership. Do not weaken required owners indiscriminately. A bounded cache should have a documented key, capacity/eviction, and lifetime. Repeat the same navigation cycles and verify intended instance lifetimes after the fix.

XCODE-14 — Answer

Short answer: No, memory growth can come from temporary image buffers, allocation churn, reachable caches, or unintended retention as well as reference cycles. Compare surviving allocations across repeated interactions and inspect what owns them. A clean Leaks result does not prove that a reachable cache is bounded or that the app's memory budget is acceptable.

Detailed explanation:

Illustrative image-cache policy sets an advisory byte-cost target and declares an explicit invalidation point; actual decoded cost is supplied by the image pipeline.

SWIFT
@MainActor
final class ThumbnailCache {
    private let storage = NSCache<NSURL, UIImage>()
    init(costTargetBytes: Int) {
        precondition(costTargetBytes > 0)
        storage.totalCostLimit = costTargetBytes
    }
    func store(_ image: UIImage, url: URL, decodedCostBytes: Int) {
        precondition(decodedCostBytes >= 0)
        storage.setObject(image, forKey: url as NSURL, cost: decodedCostBytes)
    }
    func clear() { storage.removeAllObjects() }
}

This UIKit/Foundation fragment gives the UI-image cache an explicit MainActor owner; call clear() at its chosen lifetime boundary. NSCache is not a hard process-memory cap and other consumers may still retain the images.

Rising memory can be legitimate cached content, transient decoded images, allocation churn, abandoned but reachable objects, or a retain cycle. Mark Allocations generations around repeated scrolling/dismissal, compare survivors and sizes, and inspect their allocation stacks and retaining owners. A reachable unbounded cache can be wasteful without appearing as an unreachable leak. Measure peak and steady-state footprint, repeated-cycle growth, and behavior under realistic image sizes on supported devices, alongside UI responsiveness and eviction correctness. Simulator memory and one average are insufficient for an iOS device budget. Avoid promising that all framework caches return memory immediately after dismissal.

XCODE-15 — Answer

Short answer: A frame capture explains the commands and resources used for a selected rendering scope, while a timeline trace shows when CPU and GPU work runs and waits over time. For intermittent stutters, correlate several affected intervals before choosing a detailed frame to inspect. One correct-looking frame or Simulator FPS cannot establish real-device performance.

Detailed explanation:

Illustrative Metal capture fragment for a supported destination and app-provided command queue, writable output URL, and frame-encoding function.

SWIFT
let manager = MTLCaptureManager.shared()
guard manager.supportsDestination(.gpuTraceDocument) else { return }
let descriptor = MTLCaptureDescriptor()
descriptor.captureObject = commandQueue
descriptor.destination = .gpuTraceDocument
descriptor.outputURL = traceURL
try manager.startCapture(with: descriptor)
defer { manager.stopCapture() }
encodeAndSubmitAffectedFrame()

Use this inside an appropriate throwing app function with Metal imported. It describes an optional capture scope; no capture was performed, and timeline analysis remains necessary for intermittent stalls.

For intermittent scrolling, record several affected intervals using Animation Hitches/SwiftUI/Core Animation and CPU/thread evidence; correlate the actual missed frames with main-thread update or rendering stages. A Metal capture provides detailed commands/resources/passes/shaders for a chosen scope. Metal System Trace adds execution/submission timing and CPU/GPU correlation across time, helping identify gaps or a limiting workload. A correct-looking frame can still be expensive, and an unaffected capture can miss the problem. Confirm tool/device support and reproduce on representative physical hardware; Simulator uses the Mac's GPU and a static screenshot has no timing history. Apple Metal tools

XCODE-16 — Answer

Short answer: No, differences in device, optimization, instrumentation, cache state, or workload can explain the result independently of the code change. Compare repeated before-and-after runs under matching conditions and report the distribution and sample count. Measure a user-visible outcome as well as the internal operation whose cost you are investigating.

Detailed explanation:

Illustrative XCTest performance-method body, using a prepared fixed fixture and app projection. Ten iterations is a configured example, not a reported sample count or result.

SWIFT
func testHistoryProjectionPerformance() {
    let fixture = makeFixedHistoryFixture()
    let options = XCTMeasureOptions()
    options.iterationCount = 10
    measure(metrics: [XCTClockMetric()], options: options) {
        _ = projectHistory(fixture)
    }
}

Place this in an XCTestCase; verify projection correctness separately and run comparable build/device/cache settings before interpreting a baseline regression.

The configurations differ in optimization, device, instrumentation, cache state, and sampling. The arithmetic ratio describes two numbers, but it does not establish production improvement attributable to the change. Use matching optimized builds, device/OS, workload, network policy, thermal/charging state, and deliberate cold/warm-cache scenarios. Capture repeated runs and report distributions with sample counts. Keep symbols so profiles remain interpretable. Signposts delimit a meaningful operation; XCTest performance tests help repeat a scenario and detect comparable regressions. Use separate sanitizer/debugger runs for correctness and an appropriate clean baseline for cost. Include loading/scroll responsiveness or another user-visible outcome rather than only one internal duration.

XCODE-17 — Answer

Short answer: Address Sanitizer is the relevant diagnostic for supported invalid memory accesses such as reading deallocated storage. It helps identify the failing access and allocation lifetime, but does not prove the absence of every leak, data race, or arithmetic error. Repair ownership and lifetime, then verify ordinary behavior with the relevant tests.

Detailed explanation:

Illustrative repaired lifetime: the value is copied while initialized storage is valid; deinitialization and deallocation happen exactly once at scope exit.

SWIFT
func copyStoredValue() -> Int {
    let pointer = UnsafeMutablePointer<Int>.allocate(capacity: 1)
    pointer.initialize(to: 42)
    defer {
        pointer.deinitialize(count: 1)
        pointer.deallocate()
    }
    return pointer.pointee
}
assert(copyStoredValue() == 42)

Ordinary value storage is preferable when no unsafe API requires a pointer; this example teaches the resource lifetime rather than recommending manual allocation.

The code reads deallocated storage. Address Sanitizer is the relevant runtime tool for supported unsafe-memory accesses. The repair removes the invalid access and assigns a clear allocation/deinitialization/deallocation owner; do not extend the pointer's lifetime with unrelated allocations. Thread Sanitizer targets exercised data races; Main Thread Checker checks supported main-thread API restrictions. ASan does not prove the absence of leaks, uninitialized-memory errors, or integer overflow. Verify scheme/destination support, inspect the first report and allocation/free stacks, and rerun the targeted test. Instrumentation changes memory and execution cost, so measure performance separately. Safe ownership and ordinary behavior tests remain necessary even with a clean diagnostic run.

XCODE-18 — Answer

Short answer: Start with a reproducible operation and correlate its network activity, CPU work, wakeups, and display or GPU use on representative devices. Control relevant conditions such as connectivity, charging, and temperature so comparisons mean something. Evaluate a proposed reduction in work against the product's required freshness and reliability, rather than claiming savings from one trace.

Detailed explanation:

Illustrative bounded sync operation triggered by an owned scheduling policy rather than unconditional rapid polling. Store/API methods are application contracts.

SWIFT
func synchronizePending(limit: Int) async throws {
    precondition(limit > 0)
    let batch = try await store.pending(limit: limit)
    guard !batch.isEmpty else { return }
    try Task.checkCancellation()
    let acknowledgements = try await api.submit(batch)
    try await store.apply(acknowledgements)
}

The backend deduplicates operation IDs; the caller coalesces triggers and owns retry/backoff and cancellation. Batching is a hypothesis to measure against freshness requirements, not a claimed battery saving.

Collect a reproducible sync scenario and nonsecret traces from supported devices with permission for any user-supplied diagnostics. Use Power Profiler's subsystem/context tracks, then correlate network activity, CPU work, display/GPU use, and wakeups with operation intervals. Record device model, connectivity, charging, brightness, and thermal conditions; compare repeated runs on the same model. Consider batching, event-driven updates, backoff, cache validation, and cancellation when work is no longer needed. Define an acceptable freshness/reliability requirement alongside reduced repeated work and power impact. Do not claim a precise battery saving from a single attached, charging session or from lower CPU alone.

Continue with Swift code exercises, Swift concurrency, and the mobile technical-lead questionnaire.

For hands-on follow-up, keep a small reproduction and consult Apple's running-app debugging guide, SwiftUI performance, and Apple's profile, fix, and verify workflow. These are tool references, not evidence that this lesson's illustrative program was measured.