ios_catalogue1-9 Exercise 3: Undo Inserts When Save Fails ========================================================== Problem: save(_:tagNames:) inserts a new Item into the context, then saves. If saving throws, the item (and any newly created tags) stay inserted but unsaved. The form shows the error and stays open; the user taps Save again; save() creates a SECOND Item, and the next successful save writes both. Fix, in CatalogueRepository: func save(_ item: Item, tagNames: [String]) throws { let wasNew = item.modelContext == nil var newTags: [Tag] = [] if wasNew { context.insert(item) } // ... existing code that finds or creates tags; collect created ones into newTags ... do { try context.save() } catch { if wasNew { context.delete(item) } for tag in newTags { context.delete(tag) } throw error } } Why retrying must not duplicate: the form keeps its own `Item?` reference as nil (adding) and creates a fresh Item inside save() on every attempt, so correctness depends on the previous attempt having left nothing behind. After the undo above, a retry starts from a clean context. For an EDIT (wasNew == false) nothing is removed: the item already existed, but its changed fields remain unsaved in the context; deciding whether to roll them back is the same question as Chapter 6's draft discussion, and a draft-based form already protects the stored item until a successful Save. Note: whether context.delete on a not-yet-saved inserted object behaves exactly as assumed here is unverified; test it with the throwing save from Exercise 2 and confirm the list shows no phantom row.