Dude1313
Dude1313

Reputation: 107

CoreData with Relationships - how to avoid duplicate updates

I have CoreData with simple relationships as you can see below. One entity Word with 4 attributes and a Chapter entity with a one to many relationship (each word figures in only one chapter and chapters contains several words). When I try to import a file with a list of words and associated chapter, the chapters which are not yet in the database are created (which is what I want) but the chapters that already exists are created a 2nd time (new same entry in coredata). Is there an option I can activate in xcdatamodel to check and avoid duplicate entries on the relation entity?

enter image description here

Code details ->

fileprivate func saveAllWords(_ items: [(name: String, definition: String, example: String, chapter: String)]?) {
    
            for item in items! {
        
        let newWord = Word(context: self.context)
        
        newWord.name = item.name.trimmingCharacters(in: .whitespaces)
        newWord.definition = item.definition.trimmingCharacters(in: .whitespaces)
        newWord.example = item.example.trimmingCharacters(in: .whitespaces)
        newWord.option = 10     // option tag indicating that it's a new entry from external fileI generate a classic word

     // 
         let myNewChapter = Chapter(context: self.context)
         myNewChapter.name = item.chapter
            
         newWord.chapter = myNewChapter
    }
            
    ……


// Save the data in Core Data
    do {
        try self.context.save()
    }
    catch {
    }

Any recommendation how to implement this uniqueness constraint to solve my duplicate issue?

Upvotes: 2

Views: 422

Answers (1)

davidev
davidev

Reputation: 8527

You have to create a constraint for the unique attribute. It looks like you want the name of the Chapter to be unique

In your xcdatamodeld select your attribute, then right constraint and add they attribute.

enter image description here

Last but not least you will have to add merge policy for your Context, mostly likely in your AppDelegate. There are different merge policy. You should check them out which fits your needs most

context.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy

Upvotes: 1

Related Questions