我不明白当我试图通过调用viewContext.execute(deleteRequest(删除所有项目时,SwiftUI不会重新绘制UI。我看到sqlite中的项目不见了。
struct CloudKitTestView: View {
@Environment(.managedObjectContext) private var viewContext
@FetchRequest(
sortDescriptors: [NSSortDescriptor(keyPath: Item.timestamp, ascending: true)],
animation: .default)
private var items: FetchedResults<Item>
var body: some View {
VStack {
Button("Remove all") {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Item")
let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
do {
try viewContext.execute(deleteRequest)
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nsError = error as NSError
fatalError("Unresolved error (nsError), (nsError.userInfo)")
}
}
List {
ForEach(items) { item in
Text("Item at (item.timestamp!, formatter: itemFormatter)")
}
.onDelete(perform: deleteItems)
}
.toolbar {
#if os(iOS)
EditButton()
#endif
Button(action: addItem) {
Label("Add Item", systemImage: "plus")
}
}
}
}
private func addItem() {
withAnimation {
let newItem = Item(context: viewContext)
newItem.timestamp = Date()
do {
try viewContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nsError = error as NSError
fatalError("Unresolved error (nsError), (nsError.userInfo)")
}
}
}
private func deleteItems(offsets: IndexSet) {
withAnimation {
offsets.map { items[$0] }.forEach(viewContext.delete)
do {
try viewContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nsError = error as NSError
fatalError("Unresolved error (nsError), (nsError.userInfo)")
}
}
}
}
核心数据批更新不会更新内存中的对象。之后您必须手动刷新。
批处理操作绕过了常规的核心数据操作,直接在底层SQLite数据库(或任何支持持久存储的数据库(上进行操作。他们这样做是为了提高速度,但这意味着他们也不会触发你使用普通获取请求得到的所有东西。
你需要做一些像苹果核心数据批量编程指南中所示的事情:实现批量更新-执行后更新你的应用程序
原始答案
do {
let fetch: NSFetchRequest<NSFetchRequestResult> = Item.fetchRequest()
let request = NSBatchDeleteRequest(fetchRequest: fetch)
request.resultType = .resultTypeObjectIDs
let result = try viewContext.execute(request) as? NSBatchDeleteResult
let objIDArray = result?.result as? [NSManagedObjectID]
let changes = [NSDeletedObjectsKey: objIDArray]
NSManagedObjectContext.mergeChanges(fromRemoteContextSave: changes, into: [viewContext])
} catch {
let nsError = error as NSError
fatalError("Unresolved error (nsError), (nsError.userInfo)")
}