I'm trying to initiate the data so when the user installs the app for the first time it has some data. The init is not working, but why?
For CRUD operations on Core Data I'm using an `xcdatamodeld` file with an entity called `ProgrammingLanguage` that has two string attributes: “name” and “creator”. Here is the code:
struct ContentView: View {
@Environment(\.managedObjectContext) var managedObjectContext
@FetchRequest(
entity: ProgrammingLanguage.entity(),
sortDescriptors: [
NSSortDescriptor(keyPath: \ProgrammingLanguage.name, ascending: true),
]
) var languages: FetchedResults
init() {
let language = ProgrammingLanguage(context: self.managedObjectContext)
language.name = "SwiftUI"
language.creator = "Some text"
do {
try self.managedObjectContext.save()
} catch {
}
}
var body: some View {
NavigationView {
List {
ForEach(languages, id: \.self) { language in
Button(action: {
}) {
Text("Creator: \(language.creator ?? "Anonymous")")
}
}
}
}
}
}
It's as if it is not saving it. What's going on here? That init should create the data on the db and I would be able to read it on the view...