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?)
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With