I tried to follow "How to combine Core Data and SwiftUI" by deleting Persistence.swift
and replacing ContentView.swift
with the following code:
//
// ContentView.swift
// Bookworm
//
// Created by John Coxon on 10/02/2021.
//
import SwiftUI
import CoreData
struct ContentView: View {
@Environment(\.managedObjectContext) var moc
@FetchRequest(entity: Student.entity(), sortDescriptors: []) var students: FetchedResults<Student>
var body: some View {
VStack {
List {
ForEach(students, id: \.id) { student in
Text(student.name ?? "Unknown")
}
}
Button("Add") {
let firstNames = ["Ginny", "Harry", "Hermione", "Luna", "Ron"]
let lastNames = ["Weasley", "Potter", "Granger", "Lovegood"]
let chosenFirstName = firstNames.randomElement()!
let chosenLastName = lastNames.randomElement()!
let student = Student(context: self.moc)
student.id = UUID()
student.name = "\(chosenFirstName) \(chosenLastName)"
try? self.moc.save()
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
As far as I can tell this is identical to Paul's example, but it crashes with the following:
libc++abi.dylib: terminating with uncaught exception of type NSException
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'An NSManagedObject of class 'Student' must have a valid NSEntityDescription.'
Does anyone know why, and is the reason connected to the above issue?