I am trying to use Core Data with MVVM in SwiftUI, but I can't manage to make the List in my view update whenever there are changes to Core Data.
Please check this example. Why my List doesn't update if items is a Published variable?
QUESTION: How to make the List update every time I add or delete items?
Right now I need to force quit the app and open it again to see changes. I've searched for many similar questions and I wasn't able to make it work. Maybe I'm missing something obvious.
EXAMPLE CODE:
ContentView.swift
import SwiftUI
import CoreData
struct ContentView: View {
@Environment(\.managedObjectContext) private var viewContext
@StateObject var vm = ContentViewModel()
var body: some View {
NavigationView {
List {
ForEach(vm.items) { item in
Text(item.text!)
}
}
.toolbar {
ToolbarItem {
Button(action: addItem) {
Label("Add Item", systemImage: "plus")
}
}
ToolbarItem(placement: .destructiveAction){
Button(action: deleteAll) {
Image(systemName: "trash")
.foregroundColor(.red)
}
}
}
Text("Select an item")
}
}
private func addItem() {
withAnimation {
let newItem = Item(context: viewContext)
newItem.text = "List item"
do {
try viewContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
}
}
private func deleteAll() {
vm.items.forEach(viewContext.delete)
do {
try viewContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView().environment(\.managedObjectContext, PersistenceController.preview.container.viewContext)
}
}
ContentViewModel.swift
import Foundation
import CoreData
final class ContentViewModel: ObservableObject {
// Why my List doesn't update if items is a Published variable?
@Published var items: [Item] = []
let container: NSPersistentContainer = PersistenceController.shared.container
init() {
let fetchRequest = NSFetchRequest<Item>(entityName: "Item")
do {
items = try container.viewContext.fetch(fetchRequest)
} catch let error {
print("Error fetching. \(error)")
}
}
}
Persistence.swift (it's almost the same as default Core Data example file in Xcode 14)
import CoreData
struct PersistenceController {
static let shared = PersistenceController()
static var preview: PersistenceController = {
let result = PersistenceController(inMemory: true)
let viewContext = result.container.viewContext
for _ in 0..<10 {
let newItem = Item(context: viewContext)
newItem.text = "Abc"
}
do {
try viewContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
return result
}()
let container: NSPersistentContainer
init(inMemory: Bool = false) {
container = NSPersistentContainer(name: "CoreDataMVVM")
if inMemory {
container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")
}
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
container.viewContext.automaticallyMergesChangesFromParent = true
}
}
xcdatamodeld has 1 entity: Item with 1 attribute: text: String