I have a List of Core Data elements I can add. I want to be able to edit them. For that I have an "edit Sheet" View. But when I try editing the element the app crashes and I get the error "Thread 1: "-[Item setTitle:]: unrecognized selector sent to instance 0x600002479a80""
I recreated the error here:
struct ListView: View {
@Environment(\.managedObjectContext) var viewContext
@FetchRequest(sortDescriptors: []) var items: FetchedResults<Item>
@State var showEditItemSheet = false
@State var itemToEdit = Item()
var body: some View {
List {
ForEach(items) { item in
ListItemView(item: item)
.onTapGesture {
itemToEdit = item
showEditItemSheet.toggle()
}
}
}
.sheet(isPresented: $showEditItemSheet, content: {EditItemView(item: itemToEdit, showEditItemSheet: $showEditItemSheet)}
}
}
struct ListItemView: View {
@FetchRequest(sortDescriptors: []) var items: FetchedResults<Item>
@ObservedObject var item: FetchedResults<Item>.Element
var body: some View {
Text(item.title)
}
}
struct EditItemView: View {
@Environment(\.managedObjectContext) var viewContext
@State var item: FetchedResults<Item>.Element
@Binding var showEditItemSheet: Bool
@State var title = ""
var body: some View {
VStack {
TextField("Title", text: $title)
Button(action: {
item.title = title //<- Here I get the error
saveContext()
showEditItemSheet.toggle()
}, label: {Text("Save")})
}
}
private func saveContext() {
do {
try viewContext.save()
} catch {
let error = error as NSError
fatalError("Unresolved Error: \(error)")
}
}
}
I recreated the error here:
struct ListView: View {
@Environment(\.managedObjectContext) var viewContext
@FetchRequest(sortDescriptors: []) var items: FetchedResults<Item>
@State var showEditItemSheet = false
@State var itemToEdit = Item()
var body: some View {
List {
ForEach(items) { item in
ListItemView(item: item)
.onTapGesture {
itemToEdit = item
showEditItemSheet.toggle()
}
}
}
.sheet(isPresented: $showEditItemSheet, content: {EditItemView(item: itemToEdit, showEditItemSheet: $showEditItemSheet)}
}
}
struct ListItemView: View {
@FetchRequest(sortDescriptors: []) var items: FetchedResults<Item>
@ObservedObject var item: FetchedResults<Item>.Element
var body: some View {
Text(item.title)
}
}
struct EditItemView: View {
@Environment(\.managedObjectContext) var viewContext
@State var item: FetchedResults<Item>.Element
@Binding var showEditItemSheet: Bool
@State var title = ""
var body: some View {
VStack {
TextField("Title", text: $title)
Button(action: {
item.title = title //<- Here I get the error
saveContext()
showEditItemSheet.toggle()
}, label: {Text("Save")})
}
}
private func saveContext() {
do {
try viewContext.save()
} catch {
let error = error as NSError
fatalError("Unresolved Error: \(error)")
}
}
}