How to remove duplicate objects from CoreData in Swift?

I have a networking method which returns 33 results. I save it in a CoreData database. Networking method starts every time an App launches (in ViewDidLoad). After every launch my CoreData database turns to be filled in with the same 33 results. So every launch I have 33, 66, 99, etc entries in it with the same names and attributes.

In my Entity Currency I have a unique attribute id like shortName (EUR, USD, etc).

How can I check what I have in CoreData after every Networking and if that shortName already exists just update its another attribute currentValue? And if there is no such shortName then fully create and save there.

The goal is to have only 33 entity's in my CoreData with recent information from Networking.

Thank you for a help in advance!

Answered by artexhibit in 701711022

Here is a solution worked for me:

let request: NSFetchRequest<Currency> = Currency.fetchRequest()
        request.predicate = NSPredicate(format: "id = %@", id)
        
        do {
            let fetchResult = try context.fetch(request)
            if fetchResult.count > 0 {
                for doubledData in fetchResult {
                    context.delete(doubledData)
                }
            }
Accepted Answer

Here is a solution worked for me:

let request: NSFetchRequest<Currency> = Currency.fetchRequest()
        request.predicate = NSPredicate(format: "id = %@", id)
        
        do {
            let fetchResult = try context.fetch(request)
            if fetchResult.count > 0 {
                for doubledData in fetchResult {
                    context.delete(doubledData)
                }
            }

Actually the above will wipe all of your records because it doesn't select the winning objectID out of the collection of multiple results. Any good database design begins with data normalization, unique keys etc ...: Take a look at the following code by apple on how to dedupe core data records: https://developer.apple.com/documentation/coredata/synchronizing_a_local_store_to_the_cloud see CoreDataStack class

How to remove duplicate objects from CoreData in Swift?
 
 
Q