'Core data creates keeps populating with default values and doesn't save on close
I am fairly new to core data. I am trying to make a form where each time I add a section header and text from a sheet view, it appears within a new section. The problem I am having is every time I open the sheet view to enter the section header and text saved via core data, a big list of my default values of List Name and List Section appears on the main screen upon dismissing the sheet view. They also disappear after a relaunch so I don't think I am saving the data correctly.
I currently have the core data entity of Lists
with the attributes of listName
and listSection
which are used in my form as seen in the image.
struct ContentView: View {
@Environment(\.managedObjectContext) var moc
@FetchRequest(sortDescriptors: []) var lists: FetchedResults<Lists>
var body: some View {
NavigationView {
Form() {
ForEach(lists) { list in
Section(header: Text(list.listSection ?? "List Section")) {
NavigationLink {
Text("Next Page")
} label: {
Text(list.listName ?? "List Name")
}
}
}
}
}
}
I create this data via a sheet view. I also use the var dismiss to hide the sheet view, bringing me back to my main view code shown above.
struct AddList: View {
@Environment(\.dismiss) var dismiss
@State private var listNameEntry: String = ""
@State private var listSectionEntry: String = ""
@Environment(\.managedObjectContext) var moc
@FetchRequest(sortDescriptors: []) var lists: FetchedResults<Lists>
var body: some View {
let list = Lists(context: moc) //used to save to core data
Form {
Section() {
TextField("List Name", text: $listNameEntry) {
list.listName = listNameEntry
}
TextField("List Section", text: $listSectionEntry) {
list.listSection = listSectionEntry
}
}
Section() {
Button("Done") {
try? moc.save()
dismiss()
}
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|