Batch updating one to many relationships between two entities

Hi all,

I have 2 CoreData entities, "Person" (staff members) and "Role" (their job title, which they can have more than one of). I'm syncing all of these entities from two corresponding API endpoints.

After syncing everything, I'm trying to run a method that loops through all of the roles (there are a few thousand of them) and assign them to the corresponding "person" (there are slightly less people, but still in the low 1000's). The following works, but it's understandable slow:

public func setPeopleToRoles() async throws {

        DataStore.shared.backgroundContext.performAndWait {

            let fetchRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "Role")

            do {

                guard let roles = try DataStore.shared.backgroundContext.fetch(fetchRequest) as? [Role] else { return }



                let _ = roles.map { $0 }.compactMap {

                    if let personModel = PeopleFetcher.shared.fetchPersonFromCache(personId: $0.employee) {

                        $0.person = personModel

                    }

                }



            }catch {

                print(error)

            }



            if DataStore.shared.backgroundContext.hasChanges {

                do {

                    try DataStore.shared.backgroundContext.save()

                    print("People to Roles Saved")

                }catch {

                    print("Error caching events to CoreData: \(error)")

                }

                DataStore.shared.backgroundContext.reset()

            }

        }

    }

Is there a way I can refactor this into an NSBatchUpdate? All the information I found involves updating properties with the same value (i.e. setting "completed" to true).

Thanks in advance,

  • Scott
Batch updating one to many relationships between two entities
 
 
Q