From 9f397b433735d3fbba83e01601d00a8b96be19a9 Mon Sep 17 00:00:00 2001 From: John Estropia Date: Mon, 10 Jun 2019 18:34:15 +0900 Subject: [PATCH] Prevent crashing when DataStack is deallocated ahead of ListMonitor and child objects --- Sources/From.swift | 12 ++++++++++-- Sources/ListMonitor.swift | 11 +++++++++-- 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/Sources/From.swift b/Sources/From.swift index e75a1bb..5a9b778 100644 --- a/Sources/From.swift +++ b/Sources/From.swift @@ -140,8 +140,16 @@ public struct From { } internal func applyToFetchRequest(_ fetchRequest: CoreStoreFetchRequest, context: NSManagedObjectContext, applyAffectedStores: Bool = true) throws { - - fetchRequest.entity = context.parentStack!.entityDescription(for: EntityIdentifier(self.entityClass))! + + guard let parentStack = context.parentStack else { + + CoreStore.log( + .warning, + message: "Attempted to perform a fetch but the \(cs_typeName(DataStack.self)) has already been deallocated." + ) + throw CoreStoreError.unknown + } + fetchRequest.entity = parentStack.entityDescription(for: EntityIdentifier(self.entityClass))! guard applyAffectedStores else { return diff --git a/Sources/ListMonitor.swift b/Sources/ListMonitor.swift index 9d8ab88..30f134b 100644 --- a/Sources/ListMonitor.swift +++ b/Sources/ListMonitor.swift @@ -963,8 +963,15 @@ public final class ListMonitor: Hashable { return } - - try! newFetchedResultsController.performFetchFromSpecifiedStores() + do { + + try newFetchedResultsController.performFetchFromSpecifiedStores() + } + catch { + + // DataStack may have been deallocated + return + } self.fetchedResultsControllerDelegate.taskGroup.notify(queue: .main) { self.fetchedResultsControllerDelegate.enabled = false