From 670047af6fca6bbab574358bcef5e70ce1cff3bf Mon Sep 17 00:00:00 2001 From: Shadowfacts Date: Tue, 26 Nov 2024 23:26:35 -0500 Subject: [PATCH] Fix potential race between adding notification to NSManagedObjectContext and displaying VC --- Tusker/CoreData/MastodonCachePersistentStore.swift | 11 ++++++----- .../NotificationLoadingViewController.swift | 4 +++- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/Tusker/CoreData/MastodonCachePersistentStore.swift b/Tusker/CoreData/MastodonCachePersistentStore.swift index 0c9746f35..8599ce26e 100644 --- a/Tusker/CoreData/MastodonCachePersistentStore.swift +++ b/Tusker/CoreData/MastodonCachePersistentStore.swift @@ -375,13 +375,14 @@ class MastodonCachePersistentStore: NSPersistentCloudKitContainer, @unchecked Se } } - func addAll(notifications: [Pachyderm.Notification], completion: (() -> Void)? = nil) { - backgroundContext.perform { + func addAll(notifications: [Pachyderm.Notification], in context: NSManagedObjectContext? = nil, completion: (() -> Void)? = nil) { + let context = context ?? backgroundContext + context.perform { let statuses = notifications.compactMap { $0.status } let accounts = notifications.map { $0.account } - statuses.forEach { self.upsert(status: $0, context: self.backgroundContext) } - accounts.forEach { self.upsert(account: $0, in: self.backgroundContext) } - self.save(context: self.backgroundContext) + statuses.forEach { self.upsert(status: $0, context: context) } + accounts.forEach { self.upsert(account: $0, in: context) } + self.save(context: context) completion?() statuses.forEach { self.statusSubject.send($0.id) } accounts.forEach { self.accountSubject.send($0.id) } diff --git a/Tusker/Screens/Notifications/NotificationLoadingViewController.swift b/Tusker/Screens/Notifications/NotificationLoadingViewController.swift index d1c59acbe..82994b919 100644 --- a/Tusker/Screens/Notifications/NotificationLoadingViewController.swift +++ b/Tusker/Screens/Notifications/NotificationLoadingViewController.swift @@ -48,7 +48,9 @@ class NotificationLoadingViewController: UIViewController { do { let (notification, _) = try await mastodonController.run(request) await withCheckedContinuation { continuation in - mastodonController.persistentContainer.addAll(notifications: [notification]) { + let container = mastodonController.persistentContainer + let context = container.viewContext + container.addAll(notifications: [notification], in: context) { continuation.resume() } }