How to deduplicate entities with relationships in NSPersistentCloudKitContainer?

In my app I have a defaultJournal: Journal, that automatically gets added on the user's device on launch. There should only be one "default" journal, and I know that deduplication as shown in the Apple Demo, is the correct approach to ensure this on multiple devices. Journal looks something like:

class Journal: NSManagedObject {
  @NSManaged var isDefaultJournal: Bool
  @NSManaged var entries: Set<JournalEntry>?
}

Since Journal has a relationship to entries, how can I deduplicate it ensuring that I don't orphan or delete the entries?

I am worried that the entries aren't guaranteed to be synced, when we discover a duplicate journal in processPersistentHistory.

This would lead to either orphaned or deleted entries depending on the deletion rule.

How can one handle deduplicating entities with relationships?

For example here is my remove function:

    func remove(duplicateDefaultCalendarNotes: [Journal], winner: Journal, on context: NSManagedObjectContext) {
        duplicateDefaultCalendarNotes.forEach { journal in
            defer { context.delete(journal) }
 
            // FIXME: What if all of the journal entries have not been synced yet from the cloud?
            // Should we fetch directly from CloudKit instead? (could still lead to orphaned/deleted journal that have not yet been uploaded)

            guard let entries = journal.entries else { return }

            entries.forEach {
                $0.journal = winner
            }
        }
    }

A missing tag on a post isn't that bad, but deleting a user's journal is unacceptable. What is the best strategy to handle this?

Post not yet marked as solved Up vote post of mikeyM Down vote post of mikeyM
791 views

Replies

I would also like to know that.