I'm learning Core Data but a strange problem confused me at the very beginning. I was using the Empty project created by Xcode and did some modifications to try to implement the feature to add a new entity in a sheet.
I wanted to track the item to be added by a @State value. However, when I open up the sheet, I have already seen the record is added before I executed any try? context.save()
. I'd like to use the @State entity to be passed down to the sheet for receiving information there and finally saved to store when hitting "confirm" (not implemented in the code). The reason I pass a whole entity object is that I want to handle Add/Edit in the same sheet.
BTW, is it correct to handle such "Entity adding" scenario like this using @State?
import SwiftUI
import CoreData
struct ContentView: View {
@Environment(\.managedObjectContext) private var viewContext
@FetchRequest(
sortDescriptors: [NSSortDescriptor(keyPath: \Item.timestamp, ascending: true)],
animation: .default)
private var items: FetchedResults<Item>
@State private var itemToAdd: Item?
var body: some View {
NavigationView {
List {
ForEach(items) { item in
NavigationLink {
Text("Item at \(item.timestamp!, formatter: itemFormatter)")
} label: {
Text(item.timestamp!, formatter: itemFormatter)
}
}
}
.toolbar {
ToolbarItem {
Button {
itemToAdd = Item(context: viewContext)
itemToAdd?.timestamp = Date()
} label: {
Label("Add Item", systemImage: "plus")
}
}
}
.sheet(item: $itemToAdd) { itemToAdd in
Text("Empty")
}
}
}
}
private let itemFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .short
formatter.timeStyle = .medium
return formatter
}()