Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

On the iPhone, Does Core Data have a way to bulk update a field for every instance of an entity that it's storing? Something like

update some_entities set some_count = 0 where some_count > 0

Or do I just have to instantiate every entity, set the value, then save it? (And if that's the answer, how could I do that in a single transaction, assuming the set is too large to fit in memory?)

like image 593
James Moore Avatar asked Dec 14 '22 01:12

James Moore


2 Answers

This is not provided by Core Data, but you could use the makeObjectsPerformSelector:withObject: method of an NSSet or NSArray of your Core Data managed objects.
Pass the setter accessor as the selector and the value as the object.

For example, if the managed objects have an attribute "name" that needs to be set the same for all:

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

You don't have to have an NSFetchedResultsController. You can use the array from an NSFetchRequest or even the NSSet from a to-many relationship among your Core Data entities.

like image 73
gerry3 Avatar answered May 20 '23 09:05

gerry3


Core Data isn't a database. If you want to bulk-update the objects, you'll have to fetch them and update the values yourself.

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

And, as gerry suggested, if the update you're doing is simple, you can use makeObjectsPerformSelector: to do the update in one line.

like image 37
Alex Avatar answered May 20 '23 09:05

Alex