SpacePod 33 CoreData Save & Fetch
We’ve done the ground work in the last few videos, and we’re finally ready to save to and fetch from our CoreData store.
Steps
- Add
.environment
and specify\.managedObjectContext
keypath - Add
@Environment
varviewContext
to PodListView - Create
@FetchRequest
and sort by date descending - Save context on getPods completion
- Fix previews
SpacePodApp.swift
...
ContentView()
.environment(\.managedObjectContext, PersistenceController.shared.container.viewContext)
...
PodListView
//@State var pods: [Pod] = []
@Environment(\.managedObjectContext) private var viewContext
@FetchRequest(
entity: Pod.entity(),
sortDescriptors: [NSSortDescriptor(key: "date", ascending: false)]
) var pods: FetchedResults<Pod>
...
private func getPods() async {
if await Network().getPods() != nil {
do {
try viewContext.save()
} catch {
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
}
}
...
PodListView()
.environment(\.managedObjectContext, PersistenceController.preview.container.viewContext)
Resources
Core Data Lab Donny Wals on Core Data Sarunw on What is @Environment in SwiftUI