Monday, September 8, 2014 [Tweets] [Favorites]

Core Data Batch Updates

Geppy Parziale:

First of all, Apple introduced a new method executeRequest:error: in the NSManagedObjectContext class. It is very similar to the executeFetchRequest:error: method that you can use to perform a fetch request to populate the Managed Object Context. Its first argument is a NSBatchUpdateRequest. This is a new class, subclass of the NSPersistentStoreRequest recently introduced in iOS 7, and provides very similar functionalities to its sibling NSFetchRequest. 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 the executeRequest:error: method. After its execution, this method returns an NSBatchUpdateResult object (subclass of NSPersistentStoreResult), the result property of which contains the batch updates result value(s). You can define the type of results you want from the executeRequest:error:, when you define the NSBatchUpdateRequest. 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.)


Stay up-to-date by subscribing to the Comments RSS Feed for this post.

Leave a Comment