From b264305cfaef107369e960d96d5cfb2db88fec52 Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Sun, 23 Jun 2024 12:48:59 -0700 Subject: [PATCH] Fix bug saving authors in database. --- .../Related Objects/DatabaseLookupTable.swift | 25 +++++++++++++++---- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/Database/Sources/Database/Related Objects/DatabaseLookupTable.swift b/Database/Sources/Database/Related Objects/DatabaseLookupTable.swift index 2501ea92d..8737a7c05 100644 --- a/Database/Sources/Database/Related Objects/DatabaseLookupTable.swift +++ b/Database/Sources/Database/Related Objects/DatabaseLookupTable.swift @@ -137,12 +137,27 @@ private extension DatabaseLookupTable { func uniqueRelatedObjects(with objects: [DatabaseObject]) -> [DatabaseObject] { - // All of our objects that conform to DatabaseObject are Hashable. - // If that’s ever not true, this will crash when run from Xcode. - let objectSet = Set(objects as! [AnyHashable]) - return Array(objectSet) as! [DatabaseObject] + var relatedObjectIDs = Set() + var relatedObjectsUniqueArray = [DatabaseObject]() + + for object in objects { + guard let relatedObjects = object.relatedObjectsWithName(relationshipName) else { + assertionFailure("uniqueRelatedObjects: expected every object to have related objects.") + continue + } + for relatedObject in relatedObjects { + let databaseID = relatedObject.databaseID + if !relatedObjectIDs.contains(databaseID) { + relatedObjectIDs.insert(databaseID) + relatedObjectsUniqueArray.append(relatedObject) + } + } + } + + assert(relatedObjectIDs.count == relatedObjectsUniqueArray.count) + return relatedObjectsUniqueArray } - + func syncRelatedObjectsAndLookupTable(_ object: DatabaseObject, _ lookupTable: RelatedObjectIDsMap, _ database: FMDatabase) { guard let relatedObjects = object.relatedObjectsWithName(relationshipName) else {