Jackson Tale
Jackson Tale

Reputation: 25842

CoreData - Is there a good way to upsert items?

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?

Upvotes: 11

Views: 2620

Answers (2)

Amadeu Cavalcante Filho
Amadeu Cavalcante Filho

Reputation: 2398

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

Upvotes: 8

Tim
Tim

Reputation: 60150

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.

Upvotes: 4

Related Questions