remove duplicates in coredata in swift

To remove duplicates in CoreData, you can make use of the NSSet class. Here's a sample code that you can use:

main.swift
let fetchRequest:NSFetchRequest<CDCustomObject> = CDCustomObject.fetchRequest() 
let sortDescriptor = NSSortDescriptor(key: "key1", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor]

do {
    let results = try context.fetch(fetchRequest)
    let uniques = NSMutableOrderedSet(array: results) // remove duplicates
    let finalResults = uniques.compactMap { $0 as? CDCustomObject } // convert back to array
    } catch {    
        let fetchError = error as NSError
        print(fetchError)
}
509 chars
13 lines

Here, CDCustomObject is the entity name for the CoreData object you want to remove duplicates from.

First, make a fetch request for the object with a sorting descriptor. The sorting descriptor help in sorting the order in which CoreData objects will be fetched.

Next, we use NSMutableOrderedSet to remove duplicates from the fetch results. This is done by casting the results to an ordered set which removes duplicates automatically.

Finally, we convert the ordered set back to an array using compactMap, to remove any nil values that may have been introduced into the set.

After executing this code, the finalResults array will contain only unique instances of the CDCustomObject.

gistlibby LogSnag