I am new to SwiftUI and one thing I am struggling to understand is how do we call CoreData in ObservableObject?
I have the following code in place.
SimpleTodoModel.xcdatamodeld Inside there is a simple entities name: Task
Main Application
import SwiftUI
@main
struct NewApp: App {
let persistentContainer = CoreDataManager.shared.persistentContainer
var body: some Scene {
WindowGroup {
ContentView().environment(\.managedObjectContext, persistentContainer.viewContext)
}
}
}
CoreDataManager and ContentView
import Foundation
import CoreData
class CoreDataManager {
let persistentContainer: NSPersistentContainer
static let shared: CoreDataManager = CoreDataManager()
private init() {
persistentContainer = NSPersistentContainer(name: "SimpleTodoModel")
persistentContainer.loadPersistentStores { description, error in
if let error = error {
fatalError("Unable to initialize Core Data \(error)")
}
}
}
}
struct ContentView: View {
@EnvironmentObject var obs : observer
@State private var title: String = ""
@State private var selectedPriority: Priority = .medium
@Environment(\.managedObjectContext) private var viewContext
@FetchRequest(entity: Task.entity(), sortDescriptors: [NSSortDescriptor(key: "dateCreated", ascending: false)]) private var allTasks: FetchedResults<Task>
private func saveTask() {
do {
let task = Task(context: viewContext)
task.title = title
task.priority = selectedPriority.rawValue
task.dateCreated = Date()
try viewContext.save()
} catch {
print(error.localizedDescription)
}
}
var body: some View {
NavigationView {
VStack {
//making a view and calling coredata values which is working perfectly
}
}
}
}
Here is where i struggle, calling coredata outside of the view in a class/ObservableObject
class observer : ObservableObject{
//How should i call the coredata instead?
//Say i want to change a piece of value in what i have saved above inside one of the Task record?
}