diff --git a/Shared/PostCollection/CollectionListModel.swift b/Shared/PostCollection/CollectionListModel.swift index 741cee7..c5ff71f 100644 --- a/Shared/PostCollection/CollectionListModel.swift +++ b/Shared/PostCollection/CollectionListModel.swift @@ -1,37 +1,38 @@ import SwiftUI import CoreData class CollectionListModel: ObservableObject { @Published var userCollections = [WFACollection]() init() { loadCachedUserCollections() } func loadCachedUserCollections() { let request = WFACollection.createFetchRequest() let sort = NSSortDescriptor(key: "title", ascending: true) request.sortDescriptors = [sort] userCollections = [] do { let cachedCollections = try PersistenceManager.persistentContainer.viewContext.fetch(request) userCollections.append(contentsOf: cachedCollections) } catch { print("Error: Failed to fetch cached user collections.") } } func clearUserCollection() { - // Make sure the userCollections property is properly populated. - // FIXME: Without this, sometimes the userCollections array is empty. - loadCachedUserCollections() + userCollections = [] + let fetchRequest: NSFetchRequest = NSFetchRequest(entityName: "WFACollection") + let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest) - for userCollection in userCollections { - PersistenceManager.persistentContainer.viewContext.delete(userCollection) + do { + try PersistenceManager.persistentContainer.persistentStoreCoordinator.execute( + deleteRequest, with: PersistenceManager.persistentContainer.viewContext + ) + } catch { + print("Error: Failed to purge cached collections.") } - PersistenceManager().saveContext() - - userCollections = [] } }