CoreData 删除后的列表刷新
Posted
技术标签:
【中文标题】CoreData 删除后的列表刷新【英文标题】:List refresh after CoreData deletion 【发布时间】:2021-08-29 17:39:58 【问题描述】:我有一个包含 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 实体中删除记录)但视图中的列表行未刷新。这可能是什么问题?
【问题讨论】:
【参考方案1】:一些谷歌搜索显示批量删除需要更多步骤才能工作(来自here 的信息)
...
使用NSBatchDeleteRequest
时的一些重要注意事项是:
NSBatchDeleteRequest
直接修改了NSPersistentStore
,不加载任何数据到内存中。
NSBatchDeleteRequest
不会修改 NSManagedObjectContext
。如果需要通知NSManagedObjectContext
批量删除,请使用mergeChanges(fromRemoteContextSave:, into:)
(如示例中所示)。
// 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]
)
【讨论】:
以上是关于CoreData 删除后的列表刷新的主要内容,如果未能解决你的问题,请参考以下文章
从 CoreData 刷新 NSTreeController
过滤后的 SwiftUI CoreData 列表中的 Sum 属性