问题描述
我有项目列表并从 CoreData 中获取它们
I have List of items and fetch them from CoreData
@FetchRequest(
sortDescriptors: [NSSortDescriptor(keyPath: \Item.timestamp, ascending: true)],
animation: .default)
private var items: FetchedResults<Item>
var body: some View {
List {
ForEach(items) { item in
Text("Item at \(item.timestamp!, formatter: itemFormatter)")
}
}
}
我尝试更新所有项目,但 UI 显示旧值.项目实体在 sqlite 中有新值.
I try to upate all items but UI shows old values. Item entity has new values in sqlite.
let request = NSBatchUpdateRequest(entity: Item.entity())
request.propertiesToUpdate = ["timestamp": Date()]
do {
try viewContext.execute(request)
} catch {
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
推荐答案
Core Data 批量更新不会更新内存中的对象.之后您必须手动刷新.
Core Data batch updates do not update the in-memory objects. You have to manually refresh afterwards.
批量操作绕过普通的 Core Data 操作,直接在底层 SQLite 数据库(或任何支持持久存储的数据库)上操作.他们这样做是为了提高速度,但这意味着他们也不会触发您使用正常获取请求获得的所有内容.
Batch operations bypass the normal Core Data operations and operate directly on the underlying SQLite database (or whatever is backing your persistent store). They do this for benefits of speed but it means they also don't trigger all the stuff you get using normal fetch requests.
您需要执行 Apple 的 Core Data Batch Programming Guide:Implementing Batch Updates - Updating Your Application After Execution 中所示的操作
You need to do something like shown in Apple's Core Data Batch Programming Guide: Implementing Batch Updates - Updating Your Application After Execution
do {
let request = NSBatchUpdateRequest(entity: Item.entity())
request.resultType = .updatedObjectIDsResultType
request.propertiesToUpdate = ["timestamp": Date()]
let result = try viewContext.execute(request) as? NSBatchUpdateResult
let objectIDArray = result?.result as? [NSManagedObjectID]
let changes = [NSUpdatedObjectsKey: objectIDArray]
NSManagedObjectContext.mergeChanges(fromRemoteContextSave: changes, into: [viewContext])
} catch {
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
这篇关于项目在 CoreData 中更新后不会在 UI 中更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!