I figured it out. It was all in how I was trying to pass the data. Had to setup a new @ObservedObject in the EditItemView and use that name in the DetailView. Updated view codes below. Now the data is passed to the EditItemView.
DetailView:
import CoreData
import SwiftUI
struct DetailView: View {
@Environment(\.managedObjectContext) var moc
@ObservedObject var myItem: Item
@State private var showingEditScreen = false
var body: some View {
NavigationView {
VStack {
Text(self.myItem.name ?? "Unknown name")
Text(self.myItem.attribute ?? "Unknown attribute")
}
}
.navigationBarTitle(Text(myItem.name ?? "Unknown Item"), displayMode: .inline)
.navigationBarItems(trailing:
Button(action: {
self.showingEditScreen.toggle()
}) {
Text("Edit")
}
)
.sheet(isPresented: $showingEditScreen) {
EditItemView(editItem: self.myItem).environment(\.managedObjectContext, self.moc)
}
}
}
struct DetailView_Previews: PreviewProvider {
static let moc = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
static var previews: some View {
let item = Item(context: moc)
item.name = "Test item"
item.attribute = "Test attribute"
return NavigationView {
DetailView(myItem: item)
}
}
}
EditItemView:
import SwiftUI
struct EditItemView: View {
@Environment(\.managedObjectContext) var moc
@ObservedObject var editItem: Item
var body: some View {
Text(self.editItem.name ?? "Unknown name")
}
}
struct EditItemView_Previews: PreviewProvider {
static let moc = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
static var previews: some View {
let item = Item(context: moc)
item.name = "Test item"
return NavigationView {
EditItemView(editItem: item)
}
}
}