2015-02-05 Swift example of a batch update in Core Data

Last edit

Summary: Here's a Swift example of doing a batch update in Core Data: let updateRequest = NSBatchUpdateRequest(entityName: ContentItem.entityName()) . . .

Changed:

< let updateRequest = NSBatchUpdateRequest("some_entity_name")

to

> let updateRequest = NSBatchUpdateRequest("some_entity_name")
>
> let predicateIsRead = NSPredicate(format: "isRead = %@", NSNumber(bool: true))
> updateRequest.predicate = predicateIsRead
> updateRequest.propertiesToUpdate = [
> ContentItemAttributes.isRead.rawValue: NSNumber(bool: false)
> ]
> updateRequest.resultType = NSBatchUpdateRequestResultType.UpdatedObjectsCountResultType

Changed:

< let predicateIsRead = NSPredicate(format: "isRead = %@", NSNumber(bool: true))
< updateRequest.predicate = predicateIsRead
< updateRequest.propertiesToUpdate = [
< ContentItemAttributes.isRead.rawValue: NSNumber(bool: false)
< ]
< updateRequest.resultType = NSBatchUpdateRequestResultType.UpdatedObjectsCountResultType

<
< var error: NSError?
< let updateResult = objectContext.executeRequest(updateRequest, error: &error) as NSBatchUpdateResult?
< if let result = updateResult {
< let count = result.result as Int
< log.verbose("Updated \(count) rows")
< } else {
< log.error("Error during batch update: \(error?.localizedDescription)")
< }

to

> var error: NSError?
> let updateResult = objectContext.executeRequest(updateRequest, error: &error) as NSBatchUpdateResult?
> if let result = updateResult {
> let count = result.result as Int
> println("Updated \(count) rows")
> } else {
> println("Error during batch update: \(error?.localizedDescription)")
> }
> Note that you'll need to update the objects in memory. The above code just prints the row count. If you have stuff displayed in the user interface, use [http://stackoverflow.com/a/27403372/1085556 this answer on Stack Overflow] to adjust the above code.


Here's a Swift example of doing a batch update in Core Data:

	let updateRequest = NSBatchUpdateRequest("some_entity_name")
	
	let predicateIsRead = NSPredicate(format: "isRead = %@", NSNumber(bool: true))
	updateRequest.predicate = predicateIsRead
	updateRequest.propertiesToUpdate = [
		ContentItemAttributes.isRead.rawValue: NSNumber(bool: false)
	]
	updateRequest.resultType = NSBatchUpdateRequestResultType.UpdatedObjectsCountResultType
		
	var error: NSError?
	let updateResult = objectContext.executeRequest(updateRequest, error: &error) as NSBatchUpdateResult?
	if let result = updateResult {
		let count = result.result as Int
		println("Updated \(count) rows")
	} else {
		println("Error during batch update: \(error?.localizedDescription)")
	}

Note that you'll need to update the objects in memory. The above code just prints the row count. If you have stuff displayed in the user interface, use this answer on Stack Overflow to adjust the above code.