Prevent Data Retention in Core Data When View is Dismissed

Prerequisite Information

I am trying to use Core Data in my SwiftUI app. I have created 3 entities, a Record, a Header and an Entry. The Record contains the Header entities. The Header contain other Header or Entry entities. The Entry has a title and a value.

My List view looks like this, I fetch the records with a @FetchRequest.

NavigationView {
        List {
                ForEach(records) { record in
                        NavigationLink(destination: DetailView(headers: record.headers!.allObjects as? [Header] ?? [], isNewEntry: true)) {
                                Text(record.id!.uuidString)
                        }
                }
        }
}

In my DetailView I have a form that passes the details to other views which create a DisclosureGroup for a Header, a bold Text for a subheader, and a TextField for an Entry

let headers: [Header]
let isNewEntry: Bool
@Environment(\.managedObjectContext) var managedObjectContext

init(headers: [Header], isNewEntry: Bool = false) {
        self.headers = headers
        self.isNewEntry = isNewEntry
}

Form {
        ForEach(Array(headers.enumerated()), id: \.element) { index, header in
                HeaderView(header: header, isExpanded: Binding(
                    get: { self.expandedStates[header.id!, default: false] },
                    set: { self.expandedStates[header.id!] = $0 }
                ))
        }
}

Problem

When I press the record in the list, it takes me to the DetailView where I can write something in the TextField. Then if I slide back and do not press the save button and then press the same record again from the list, it retains the data I wrote in the TextField.

Question

How can I make it so that the data is not retained if I slide back except only when I press the save button?

Please let me know if any other information is needed or if something is unclear.

Prevent Data Retention in Core Data When View is Dismissed
 
 
Q