好吧,看来我可能已经找到了方法,但如果您发现任何问题,请告诉我。
当您进行批量更新时,您有可能获得结果(无论什么都没有)、已更新的行数或已更新的对象 ID 列表。你必须选择最后一个。
一旦你表演executeRequest
从上下文中,您需要获取对象 ID 列表,循环遍历所有对象 ID 以获得每个对象 IDNSManagedObject
由于该方法而导致故障objectWithID
上下文对象的。如果你不知道Core Data中的Faults对象是什么,here https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/CoreData/FaultingandUniquing.html是解释。
与每一个NSManagedObject
你知道,你需要使用它的方法刷新上下文refreshObject
.
完成此操作后,您需要再次执行performFetch
你的fetchedResultsController
返回到批量更新之前的位置。
告诉我我是否有什么地方错了。
这是代码:
let batchUpdate = NSBatchUpdateRequest(entityName: "myEntity")
batchUpdate.propertiesToUpdate = ["myPropertieToUpdate" : currency.amountToCompute]
batchUpdate.affectedStores = managedContext.persistentStoreCoordinator?.persistentStores
batchUpdate.resultType = .UpdatedObjectIDsResultType
var batchError: NSError?
let batchResult = managedContext.executeRequest(batchUpdate, error: &batchError) as NSBatchUpdateResult?
if let result = batchResult {
println("Records updated \((result.result as [NSManagedObjectID]).count)")
// Extract Object IDs
let objectIDs = result.result as [NSManagedObjectID]
for objectID in objectIDs {
// Turn Managed Objects into Faults
let nsManagedObject: NSManagedObject = managedContext.objectWithID(objectID)
if let managedObject = nsManagedObject as NSManagedObject? {
managedContext.refreshObject(managedObject, mergeChanges: false)
}
}
// Perform Fetch
var error: NSError? = nil
if !fetchedResultsController.performFetch(&error) {
println("error: + \(error?.localizedDescription), \(error!.userInfo)")
}
} else {
println("Could not update \(batchError), \(batchError!.userInfo)")
}
EDIT:
以下是两个链接以获得更多解释:
http://code.tutsplus.com/tutorials/ios-8-core-data-and-batch-updates--cms-22164 http://code.tutsplus.com/tutorials/ios-8-core-data-and-batch-updates--cms-22164
http://www.bignerdranch.com/blog/new-in-core-data-and-ios-8-batch-updating/ http://www.bignerdranch.com/blog/new-in-core-data-and-ios-8-batch-updating/