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.
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
| Idea | Android (Navigation Compose) | iOS (NavigationStack) |
|---|---|---|
| The container | NavHost with a route table | NavigationStack |
| A screen's address | A route object, DetailRoute(itemId: 7) | A value pushed on the stack: here the Item itself |
| Going there | navController.navigate(DetailRoute(id)) | NavigationLink(value: item) { ... } |
| The route table | composable<DetailRoute> { ... } | .navigationDestination(for: Item.self) { item in ... } |
| Back | popBackStack() | The back button, or @Environment(\.dismiss) |
| What is passed | An id; the screen loads the item | The 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:
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.
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 aTask, one turn of the main loop later, so the pop has started before the model disappears. This is an ordering precaution, not a guarantee:Taskonly schedules, and I could find no source that confirms the timing. - Hold the model in a local.
let doomed = itemkeeps the object alive for the delete even after the view has gone. - Draw nothing for a deleted model. The
if item.isDeletedguard stops the body reading properties of a deleted item if SwiftUI re-renders in between. (I believeisDeletedis 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:
(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.
Challenges
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.
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.
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.
Chapter 5 Quick Reference
- Push:
NavigationLink(value: item) { ... }; the value type must beHashable(fallback: pushitem.persistentModelID) - Route:
.navigationDestination(for: Item.self) { item in DetailView(item: item) }on the container, not inside a lazy row; no secondNavigationStackin 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)
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.
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.