0

我有一个来自 CoreData 实体的记录列表的视图,并且在视图中声明了以下 FetchRequest

@FetchRequest(entity: Locations.entity(), sortDescriptors: [NSSortDescriptor(key: "locTimestamp", ascending: false)])
var locations: FetchedResults<Locations>

我有两个删除功能,一个只删除具有给定 ID 的一条记录

func deleteLocation(forID id: UUID) {
    let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Locations")
    request.predicate = NSPredicate(format: "locID == %@", id as CVarArg)
    do {
        let location = try myContext.fetch(request) as! [NSManagedObject]
        myContext.delete(location.first!)
        try myContext.save()
    } catch let error {
        errTitle = "Error"
        errMessage = error.localizedDescription
        isError = true
    }
}

这工作正常,因此在视图中包含记录的列表被刷新,第二个用于删除所有记录

func deleteAllLocations() {
    let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Locations")
    let deleteRequest = NSBatchDeleteRequest(fetchRequest: request)
    do {
        try myContext.execute(deleteRequest)
        try myContext.save()
    } catch let error {
        errTitle = "Error"
        errMessage = error.localizedDescription
        isError = true
    }
}

已执行(从 CoreData 实体中删除记录)但视图中的列表行未刷新。这里可能是什么问题?

4

1 回答 1

0

一些谷歌搜索显示批量删除需要更多步骤才能工作(来自此处的信息)

...

使用时的一些重要注意事项NSBatchDeleteRequest是:

  1. NSBatchDeleteRequest直接修改NSPersistentStore而不将任何数据加载到内存中。
  2. AnNSBatchDeleteRequest不会修改NSManagedObjectContext. mergeChanges(fromRemoteContextSave:, into:)如果需要通知 aNSManagedObjectContext批量删除,请按示例中所示使用。
// Specify a batch to delete with a fetch request
let fetchRequest: NSFetchRequest<NSFetchRequestResult>
fetchRequest = NSFetchRequest(entityName: "Business")

// Create a batch delete request for the
// fetch request
let deleteRequest = NSBatchDeleteRequest(
    fetchRequest: fetchRequest
)

// Specify the result of the NSBatchDeleteRequest
// should be the NSManagedObject IDs for the
// deleted objects
deleteRequest.resultType = .resultTypeObjectIDs

// Get a reference to a managed object context
let context = persistentContainer.viewContext

// Perform the batch delete
let batchDelete = try context.execute(deleteRequest)
    as? NSBatchDeleteResult

guard let deleteResult = batchDelete?.result
    as? [NSManagedObjectID]
    else { return }

let deletedObjects: [AnyHashable: Any] = [
    NSDeletedObjectsKey: deleteResult
]

// Merge the delete changes into the managed
// object context
NSManagedObjectContext.mergeChanges(
    fromRemoteContextSave: deletedObjects,
    into: [context]
)
于 2021-08-29T17:58:56.743 回答