我有 NSFetchedResultsController
来管理我的 UITableView
数据源 .
我正在尝试使用 NSBatchUpdateRequest
修改名为 amountToCompute
的 NSManagedObject
的属性 . 所以我创建了批量更新:
let batchUpdate = NSBatchUpdateRequest(entityName: "MyEntity")
batchUpdate.propertiesToUpdate = ["amountToCompute" : newAmount]
batchUpdate.resultType = .UpdatedObjectIDsResultType
我执行它:
var batchError: NSError?
let batchResult = managedContext.executeRequest(batchUpdate, error: &batchError) as! NSBatchUpdateResult?
要更新我当前的托管上下文,我更新managedContext中的每个managedObject并执行 fetchedResultsController
的新提取:
if let result = batchResult {
let objectIDs = result.result as! [NSManagedObjectID]
for objectID in objectIDs {
let managedObject: NSManagedObject = managedContext.objectWithID(objectID)
if !managedObject.fault {
managedContext.refreshObject(managedObject, mergeChanges: true)
}
if !fetchedResultsController.performFetch(&error) {
println("error: + \(error?.localizedDescription), \(error!.userInfo)")
}
}
}
我实现了委托 NSFetchedResultsControllerDelegate
的一些方法来管理 NSFetchedResultsController
发送的结果中的更改:
func controllerWillChangeContent(controller: NSFetchedResultsController) {
tableView.beginUpdates()
}
func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
switch type {
...
case .Update:
reloadRowsAtIndexPaths([indexPath!], animation: reloadRowsWithAnimation)
let myManagedObject = anObject as! MyManagedObject
println("update : \(myManagedObject.amountToCompute)")
...
}
}
func controllerDidChangeContent(controller: NSFetchedResultsController) {
tableView.endUpdates()
}
我在我的8.4 iOS模拟器上运行应用程序,一切都很顺利 . println("update : \(myManagedObject.amountToCompute)")
打印新值 .
我在iPhone 6 8.4.1上运行应用程序并且值未更新, println("update : \(myManagedObject.amountToCompute)")
打印旧值 . 新值已正确保存,但更改不会出现在我的表视图中,而是在模拟器上进行 .
怎么了?为什么我在模拟器上或在我的设备上可能会有所不同 . 版本并不完全相同,但我怀疑Apple在上次更新中触及了Core Data架构 .
1 回答
这是一个不寻常的,但已知的问题,我遇到了自己,并花了几天拔出我的头发,直到找到这篇博文,这对我有用 .
https://stevenpsmith.wordpress.com/2011/08/12/nsfetchedresultscontroller-and-core-data-managed-object-updates/
它归结为添加这一行代码将staleness间隔设置为零:
[context setStalenessInterval:0];
如果我正在阅读你的帖子,你就会遇到同样的问题 . :)