Same issue - any solution?
Post
Replies
Boosts
Views
Activity
Another update to this question: I recreated this toy app WITHOUT using CoreData, instead archiving to the FileManager .documentDirectory. The app did NOT exhibit the fatal crash, even though all other code was the same (e.g., the category headers were still computed properties, etc.). I then returned to the original, posted, CoreData version of the app and removed:
do { try viewContext.save() } catch { print("Failure to save context: \(error)") }
from the deleteItem() function. This eliminated the fatal crash! Obviously it's not a viable solution - users need to be able to edit the list - but it tells me exactly where the problem is. I still don't understand why, though, or how to solve it. Any guidance is most welcome.
Update to my question: I attempted to convert the computed properties to @Published properties with the following edits to my AppData code (and by calling the updateSortedList() function in my ContentView and AddNewView code. These edits did NOT solve the fatal crash or change the error code. I'm still very much stuck on this, and really welcome input. Here are my edits:
@Published var groupedByCategory: Dictionary<String, [Item]> = [:]
@Published var sortedByCategoryHeaders: [String] = []
func updateSortedList(items: [Item]) {
self.groupedByCategory = Dictionary(grouping: items.sorted(), by: {$0.category})
self.sortedByCategoryHeaders = groupedByCategory.map({ $0.key }).sorted(by: {$0 < $1})
}
init(viewContext: NSManagedObjectContext) {
self.viewContext = viewContext
let request = NSFetchRequest<Item>(entityName: "ItemEntity")
request.sortDescriptors = [NSSortDescriptor(keyPath: \Item.name, ascending: true)]
fetchedResultsController = NSFetchedResultsController(fetchRequest: request,
managedObjectContext: viewContext,
sectionNameKeyPath: nil,
cacheName: nil)
super.init()
fetchedResultsController.delegate = self
do {
try fetchedResultsController.performFetch()
guard let items = fetchedResultsController.fetchedObjects else {
return
}
self.items = items
} catch {
print("failed to fetch items: \(error)")
}
self.groupedByCategory = Dictionary(grouping: items.sorted(), by: {$0.category})
self.sortedByCategoryHeaders = groupedByCategory.map({ $0.key }).sorted(by: {$0 < $1})
} // end of init()