Database Reference
In-Depth Information
Luckily, in iOS 8 Apple introduced batch updates, a new way to update Core Data
objects without having to fetch anything into memory. This new technique greatly
reduces the amount of time and memory that you need to make those huge kinds
of updates.
The new technique bypasses the NSManagedObjectContext and goes straight to the
persistent store. Let's see this in practice.
Go to viewDidLoad() and add the following lines of code after super.viewDidLoad() :
let batchUpdate = NSBatchUpdateRequest (entityName: "Venue" )
batchUpdate. propertiesToUpdate
= [ "favorite" : NSNumber (bool: true )]
batchUpdate. affectedStores = coreDataStack . psc . persistentStores
batchUpdate. resultType = . UpdatedObjectsCountResultType
var batchError: NSError ?
let batchResult =
coreDataStack . context . executeRequest (batchUpdate,
error: &batchError) as NSBatchUpdateResult ?
if let result = batchResult {
println ( "Records updated \(result. result ) " )
} else {
println ( "Could not update \(batchError) , \(batchError!. userInfo ) " )
}
The classic use case for batch updates is the “Mark all as read” feature in a
messaging application or an e-mail client. For this sample app, you're going to do
something more fun. Since you love bubble tea so much, you're going to mark
every Venue in Core Data as your favorite. :]
You create an instance of NSBatchUpdateRequest with the entity that you want to
update— Venue in this case. You set up your batch update request by setting
propertiesToUpdate to a dictionary that contains the key path of the attribute you
want to update, favorite , and its new value.
You also have to set affectedStores to your persistent store coordinator's
persistentStores array. Finally, you set the result type to return a count and
execute your batch update request.
Build and run your sample app. If everything works properly, you'll see the
following printed to your console log:
Search WWH ::




Custom Search