Is there a bulk update operation for all objects in Core Data?

On iPhone, does Core Data have the ability to bulk update a field for each instance of the object that it stores? Sort of

update some_entities set some_count = 0 where some_count> 0

Or do I just need to instantiate each object, set a value, and then save it? (And if this is the answer, how can I do this in one transaction, considering that the set is too large to fit into memory?)

+4
source share
3 answers

It is not provided by Core Data, but you can use the makeObjectsPerformSelector:withObject: NSSet or NSArray method for objects controlled by master data.
Pass the setter accessory as a selector and value as an object.

For example, if managed objects have an attribute "name" that should be set the same for everyone:

 [[fetchedResultsController fetchedObjects] makeObjectsPerformSelector:@selector(setName:) withObject:@"name for all"]; 

You do not need to have an NSFetchedResultsController. You can use an array from NSFetchRequest or even NSSet from a relationship to many of your Core Data objects.

+7
source

Master data is not a database. If you want to update objects in bulk, you will have to retrieve them and update the values โ€‹โ€‹yourself.

A good way to do this would be to fetch, say, 100 at a time (using NSFetchRequest with a set of fetchLimit ), update them, and then save the context of the managed entity. Wet, rinse, repeat until all objects are updated.

And, as Jerry suggested, if the update you are doing is simple, you can use makeObjectsPerformSelector: to update on a single line.

+4
source

No, Core Data does not have a bulk update feature. If you are limited by memory, you might consider changing the data model to simplify; instead of storing an absolute counter for each object, keep track of the main value for a group of objects and store the delta from this value for each object.

Basic data can definitely be disappointing at times for those of us who are used to thinking in terms of SQL.

+2
source

All Articles