diff --git a/Packages/ComposeUI/Sources/ComposeUI/CoreData/DraftsPersistentContainer.swift b/Packages/ComposeUI/Sources/ComposeUI/CoreData/DraftsPersistentContainer.swift index 06c4679d..c4a5a3ab 100644 --- a/Packages/ComposeUI/Sources/ComposeUI/CoreData/DraftsPersistentContainer.swift +++ b/Packages/ComposeUI/Sources/ComposeUI/CoreData/DraftsPersistentContainer.swift @@ -170,17 +170,26 @@ public class DraftsPersistentContainer: NSPersistentContainer { return } performBackgroundTask { context in + let orphanedAttachmentsReq: NSFetchRequest = DraftAttachment.fetchRequest() + orphanedAttachmentsReq.predicate = NSPredicate(format: "draft == nil") + let deleteReq = NSBatchDeleteRequest(fetchRequest: orphanedAttachmentsReq) + do { + try context.execute(deleteReq) + } catch { + logger.error("Failed to remove orphaned attachments: \(String(describing: error), privacy: .public)") + } + let allAttachmentsReq = DraftAttachment.fetchRequest() allAttachmentsReq.predicate = NSPredicate(format: "fileURL != nil") guard let allAttachments = try? context.fetch(allAttachmentsReq) else { return } - let orphaned = Set(files).subtracting(allAttachments.lazy.compactMap(\.fileURL)) - for url in orphaned { + let orphanedFiles = Set(files).subtracting(allAttachments.lazy.compactMap(\.fileURL)) + for url in orphanedFiles { do { try FileManager.default.removeItem(at: url) } catch { - logger.error("Failed to remove orphaned attachment: \(String(describing: error), privacy: .public)") + logger.error("Failed to remove orphaned attachment files: \(String(describing: error), privacy: .public)") } } completion()