Core Data Batch Updates
First of all, Apple introduced a new method
executeRequest:error:
in theNSManagedObjectContext
class. It is very similar to theexecuteFetchRequest:error:
method that you can use to perform a fetch request to populate the Managed Object Context. Its first argument is aNSBatchUpdateRequest
. This is a new class, subclass of theNSPersistentStoreRequest
recently introduced in iOS 7, and provides very similar functionalities to its siblingNSFetchRequest
. The batch request is composed of an entity (the entity containing the property or properties you want to update) and a predicate to define a subset of data you want to update. Eventually, you can also define a dictionary containing the properties you want to update and their new values.Once created, the
NSBatchUpdateRequest
is passed to theexecuteRequest:error:
method. After its execution, this method returns anNSBatchUpdateResult
object (subclass ofNSPersistentStoreResult
), theresult
property of which contains the batch updates result value(s). You can define the type of results you want from theexecuteRequest:error:
, when you define theNSBatchUpdateRequest
. You choose among three types of results:[…]
The legacy Fetch-Update-Save takes 7.2s to run on the iPhone 5s, while the new batch updates run in only 0.81 s.
Impressive is also the memory usage. As expected, since the batch updates run directly on the Persistent Store, the memory usage is incredibly lower than the old approach.
I’ve been wanting something like this for a long time. (Note that it doesn’t handle deletion.)