The Detail Screen

Personal Catalogue: iOS (Swift & SwiftUI)

Course 1 ยท Chapter 5 ยท Navigation, Detail and a Safe Delete

The list works, but tapping a row does nothing. This chapter adds a second screen that shows one item in full, moves between the two with NavigationStack, and lets you delete an item after a confirmation. The navigation part is easy. The delete part has a real trap, which the forum threads in my search describe again and again: a view that still holds a reference to a deleted SwiftData model can crash the app. Most of this chapter's care goes there.

What was run, and what was not, and what the sources say
Nothing in this chapter was compiled or run (no Mac or Xcode here). My first search confirmed value-based navigation from Apple's documentation pages and forum threads. It found nothing on confirmationDialog. My second search found a family of Apple-forum crash reports about deleted models ("backing data was detached", "invalidated", "never access a full future backing data") but no source that says which delete-and-dismiss order is safe. So the ordering used here is a reasoned precaution, and Exercise 3 asks you to test it on your own Xcode instead of trusting me.

Navigation in One Table

IdeaAndroid (Navigation Compose)iOS (NavigationStack)
The containerNavHost with a route tableNavigationStack
A screen's addressA route object, DetailRoute(itemId: 7)A value pushed on the stack: here the Item itself
Going therenavController.navigate(DetailRoute(id))NavigationLink(value: item) { ... }
The route tablecomposable<DetailRoute> { ... }.navigationDestination(for: Item.self) { item in ... }
BackpopBackStack()The back button, or @Environment(\.dismiss)
What is passedAn id; the screen loads the itemThe live Item object

That last row is the important difference. On Android, the detail screen was handed an id and loaded the item itself, so it needed Loading and NotFound states, and a deleted item simply became "not found". On iOS you hand over the object. That is convenient (an @Model object is observable, so the detail screen updates by itself when the item is edited, and can never be stale), but it is exactly what makes deletion dangerous: if the object is deleted while the screen holds it, the next time the screen reads a property there may be nothing behind it.

Step 1: Link and Destination

Apple's documentation describes NavigationLink(value:), which pushes a value onto the stack; the value's type must be Hashable. A separate modifier, navigationDestination(for:), says which view to build for a value of that type. A SwiftData @Model class is normally Hashable already, and one result in my search shows a SwiftData class used directly as a link value, but I could not confirm the conformance from a source: if Xcode says Item does not conform to Hashable, push item.persistentModelID instead and look the item up in the destination. Two changes to ListView:

// 1. In the List, wrap each row in a link that carries the item: List { ForEach(shownItems) { item in NavigationLink(value: item) { ItemRow(item: item) } } } // 2. On the VStack inside the NavigationStack (next to .navigationTitle), say where an Item goes: .navigationDestination(for: Item.self) { item in DetailView(item: item) }

Where the destination modifier sits matters. One forum answer in my search found a link failing because its matching navigationDestination was not visible from where the link was, and Apple's documentation says the modifier belongs on a nearby view. Put it on the container, not on something inside the List that is created lazily for each row. Also do not give DetailView its own NavigationStack: another forum thread reports a nested stack breaking navigation after data changes, and the detail screen is already inside the list's stack.

Step 2: The Detail Screen

Create DetailView.swift. The layout is a List with one section of labelled values; LabeledContent is the built-in "label on the left, value on the right" row. A small helper skips blank values, as the Android version's Field did.

import SwiftUI import SwiftData struct DetailView: View { let item: Item @Environment(\.modelContext) private var context @Environment(\.dismiss) private var dismiss @State private var showConfirm = false var body: some View { // Never read a deleted model: draw nothing while the screen is going away. if item.isDeleted { Color.clear } else { List { Section { Text(item.title) .font(.title2.bold()) DetailField("Type", item.typeName) DetailField("Creator", item.creator) DetailField("Format", item.formatDetail) DetailField("Year", item.releaseYear.map(String.init) ?? "") DetailField("Tags", item.sortedTags.map(\.name).joined(separator: ", ")) DetailField("Notes", item.notes) DetailField("Added", item.createdAt.formatted(date: .abbreviated, time: .omitted)) } } .navigationTitle("Details") .navigationBarTitleDisplayMode(.inline) .toolbar { ToolbarItemGroup(placement: .primaryAction) { Button("Edit", systemImage: "pencil") { /* Chapter 6 */ } Button("Delete", systemImage: "trash", role: .destructive) { showConfirm = true } } } .confirmationDialog("Delete this item?", isPresented: $showConfirm, titleVisibility: .visible) { Button("Delete", role: .destructive) { deleteItem() } Button("Cancel", role: .cancel) { } } message: { Text("\"\(item.title)\" will be removed from your catalogue. This cannot be undone.") } } } private func deleteItem() { let doomed = item dismiss() // 1. leave the screen first Task { @MainActor in // 2. delete on the next turn of the main loop do { try CatalogueRepository(context: context).delete(doomed) } catch { print("Delete failed: \(error)") // Chapter 9 shows this to the user } } } } private struct DetailField: View { let label: String let value: String init(_ label: String, _ value: String) { self.label = label self.value = value } var body: some View { if !value.isEmpty { LabeledContent(label, value: value) } } }

Why the Delete Looks Like That

The crash reports in my search share a shape: some view still holds a deleted model and reads it. One poster suspects a child view re-renders before the query updates; another reply says that clearing stale references before the delete avoids the crash; a third suggests saving first so the backing data exists. None confirms a fix, so deleteItem layers three precautions, each cheap:

  • Leave first. dismiss() pops the detail screen, so it stops being the thing that renders the item. The delete then runs in a Task, one turn of the main loop later, so the pop has started before the model disappears. This is an ordering precaution, not a guarantee: Task only schedules, and I could find no source that confirms the timing.
  • Hold the model in a local. let doomed = item keeps the object alive for the delete even after the view has gone.
  • Draw nothing for a deleted model. The if item.isDeleted guard stops the body reading properties of a deleted item if SwiftUI re-renders in between. (I believe isDeleted is a property of SwiftData models; Xcode will tell you at once if not, and Exercise 3 asks you to find the safest equivalent.)

The repository's delete (Chapter 3) saves after deleting, which is what makes the change durable. Chapter 2's delete rule means the item simply vanishes from each tag's items; the tags themselves are untouched. The list refreshes by itself because @Query notices the store changed. The confirmationDialog is a sheet that slides up with a destructive button and a Cancel button; marking the delete button role: .destructive shows it in red, as iOS users expect.

Step 3: Preview

The preview needs an item from the shared sample store. Add a helper to PreviewData and use it inside a stack so the toolbar shows:

// In PreviewData: static var sampleItem: Item { try! container.mainContext.fetch(FetchDescriptor<Item>(sortBy: [SortDescriptor(\.title)])).first! } // At the bottom of DetailView.swift: #Preview { NavigationStack { DetailView(item: PreviewData.sampleItem) } .modelContainer(PreviewData.container) }

(The NavigationStack here is only for the preview, so the toolbar has a bar to sit in; the real app's stack is in ListView.) Now run the app: add a sample item with "+", tap its row, go back with the arrow, open it again and tap the bin, then Cancel, then the bin and Delete. The row should vanish from the list. Watch the console on that last step; if the app crashes, read the message and see Exercise 3.

Compare with the Android course
In Personal Catalogue: Android (Kotlin & Compose) Chapter 5, the detail screen received an id and exposed Loading, NotFound and Found states, so a deleted item just became "not found" and the screen popped off the stack after the delete. The iOS screen gets the object itself, which removes that whole layer of state but moves the risk to the delete. The two designs are the classic trade-off: passing an id means always reading fresh data and handling absence; passing the object is simpler until the object goes away.

Challenges

Exercise 1

Add the link, the destination, DetailView and the preview. Run the app and perform the full sequence: add, open, back, delete-with-cancel, delete. Write down whether you needed to change anything (for example the Hashable fallback or the isDeleted guard), and what Xcode said.

๐Ÿ“„ View solution
Exercise 2

Add swipe-to-delete on the list rows, with the same confirmation, using .swipeActions. Decide where the "which item is waiting to be deleted" state must live, and why a @State private var showConfirm: Bool alone is not enough here.

๐Ÿ“„ View solution
Exercise 3

Test the delete ordering instead of trusting it. Try three versions in turn and record, for each, whether the app crashed, what the console said, and the iOS version: (a) delete, then dismiss(), with no guard; (b) dismiss() then delete in a Task, with no guard; (c) the chapter's version. Then say which you would ship and why.

๐Ÿ“„ View solution

Chapter 5 Quick Reference

  • Push: NavigationLink(value: item) { ... }; the value type must be Hashable (fallback: push item.persistentModelID)
  • Route: .navigationDestination(for: Item.self) { item in DetailView(item: item) } on the container, not inside a lazy row; no second NavigationStack in the detail view
  • Back: system back button, or @Environment(\.dismiss)
  • LabeledContent("Label", value: text) for label-and-value rows; skip blank values
  • Confirmation: .confirmationDialog(title, isPresented: $flag, titleVisibility: .visible) { Button("Delete", role: .destructive) { ... }; Button("Cancel", role: .cancel) { } } message: { ... }
  • Safe delete: keep the model in a local, leave the screen first, delete afterwards, and guard the body against a deleted model
  • Deleting an item clears its links; the tags remain (Chapter 2's default rule)
Not Yet Verified
Checked (two web searches on 2026-11-19): from Apple's documentation and forum threads, that NavigationLink(value:) needs a Hashable value and navigationDestination(for:) maps a value type to a view; that a destination must be visible from the link (a forum answer) and belongs on a nearby view (Apple); that a SwiftData class has been used as a link value in a forum question; that a nested NavigationStack in a detail view was reported to break navigation after data changes; and that several forum threads report crashes ("backing data was detached", "invalidated", "never access a full future backing data") when a view holds a deleted model, with suggestions to clear stale references or save first.
Not checked, from general knowledge: that @Model classes conform to Hashable; the isDeleted property; whether dismiss-then-delete in a Task is actually safe (no source confirms any order); confirmationDialog and its message closure (the search found nothing on it); LabeledContent; ToolbarItemGroup; Button(_:systemImage:role:); Date.formatted(date:time:); @Environment(\.dismiss) behaviour inside a pushed view; and all code, none of which was compiled. I did not consult Apple's pages for SwiftData deletion.
Coming next
Personal Catalogue: iOS (Swift & SwiftUI) 6 builds the add and edit form: one Form whose labels change with the item type, validation, and bindings to a draft copy of the item. It replaces Chapter 4's temporary "+" behaviour and makes the Edit button work.