I have a flag attribute on each entity in a Core Data database that I want to reset as soon as the data base has been opened. Is there a way to quickly set this flag (to the same value) for all the objects without doing a NSFetchRequest, updating the flag and saving everything back out again. I am just curious as I am doing this when the app loads so I want to make sure I use the most efficient method.
Share
No, this is one of the limitations of Core Data– it’s not designed with batch updates in mind.
If some of the objects already have the new value, you could speed things up a little by using a fetch predicate to filter them out. For example if you’re setting a boolean flag to NO, only fetch objects where it’s currently set to YES.
Also, it may help to use GCD and
dispatch_apply()to make the updates in parallel. You’ll get some boost there by using multiple cores instead of just one. Managed objects aren’t thread-safe but this should work as long (a) as you make sure all updates are complete before attempting to save changes and (b) you don’t mess with the managed objects or managed object contexts from other threads while the updates are in progress.