views:

103

answers:

3

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?)

+2  A: 

No, Core Data doesn't have a bulk update feature. If you're memory-constrained, you might consider redesigning your data model to simplify things; instead of storing an absolute count for each entity, track a master value for a group of entities and store a delta from that value per entity.

Core Data can definitely be frustrating at times for those of us used to thinking in SQL terms.

Skirwan
+2  A: 

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.

gerry3
+2  A: 

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.

Alex