Reputation: 26223
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.
Upvotes: 0
Views: 132
Reputation: 70966
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.
Upvotes: 1
Reputation: 80273
No, there is really no obvious way to avoid fetching - changing - saving. Of course, doing it on a background thread would be advisable in order not to block the UI.
However, you might want to think about your overall design and ask the question if this is really necessary.
Upvotes: 1
Reputation: 77651
Is it essential to finish this update before the app loads?
Will it affect the app if it takes a couple of seconds after loading to complete?
If so you could throw it off to a background thread. This will mean the app loads quickly but your coredata updates in the BG.
Upvotes: 1