CoreData - Is there a good way to upsert items?

2.4k views Asked by At

Just wondering whether there is a good way to upsert items in a CoreData db?

Or is there a way for me to consider a CoreData db as a set?

I mean, if I insert an item into the db and if there is already an identical redundant item there, the db ignores it. Any way to conveniently do it? or I have to query each time when I insert in order to avoid redundancy?

2

There are 2 answers

0
Tim On BEST ANSWER

No - Core Data doesn't have a way of knowing how you consider an item "identical" or "redundant." The definitions of those words can change with almost every entity you create - for example, departments in a business might have unique names, but multiple people can have the same name (and frequently do).

You can take advantage of Core Data's querying power, however, and do a quick query with an NSPredicate to find out whether a record with your chosen identifier already exists. You might factor this query out to its own method (perhaps on your managed object subclass) so that you can call it conveniently.

0
Amadeu Cavalcante Filho On

I recently read this article

https://www.upbeat.it/upsert-in-core-data/

Basically, first create a constraint on the name, then you specify the TrumpMergePolicy in the Core Data context.

managedObjectContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy