小编典典

SwiftUI:删除所有核心数据实体条目后,列表不会自动更新

swift

我知道SwiftUI使用状态驱动的渲染。所以我以为,当我删除核心数据实体条目时,带有核心数据元素的列表会立即刷新。我使用以下代码,成功清除了我的实体:

func deleteAll()
{
    let fetchRequest: NSFetchRequest<NSFetchRequestResult> = ToDoItem.fetchRequest()
    let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)

    let persistentContainer = (UIApplication.shared.delegate as! AppDelegate).persistentContainer

    do {
        try persistentContainer.viewContext.execute(deleteRequest)
    } catch let error as NSError {
        print(error)
    }
}

要使我的视图中的列表视觉上是空的,我必须事后离开视图(例如,使用“
self.presentationMode.wrappedValue.dismiss()”)并再次打开它。好像这些值仍存储在内存中的某个地方。当然这不是用户友好的,我敢肯定,我只是监督着可以立即刷新列表的内容。也许有人可以帮忙。


阅读 315

收藏
2020-07-07

共1个答案

小编典典

原因是execute(如以下详细描述-注意第一句话)不会影响托管对象的上下文,因此所有获取的对象都保留在上下文中,UI表示上下文真正呈现的内容。

因此,通常,在执行此批量操作后,您需要通知该代码(此处未提供)强制同步并重新获取所有内容。

API接口声明

// Method to pass a request to the store without affecting the contents

of the managed object context.
// Will return an NSPersistentStoreResult which may contain additional
information about the result of the action
// (ie a batch update result may contain the object IDs of the objects
that were modified during the update).
// A request may succeed in some stores and fail in others. In this
case, the error will contain information
// about each individual store failure.
// Will always reject NSSaveChangesRequests.
@available(iOS 8.0, *)
open func execute(_ request: NSPersistentStoreRequest) throws ->
NSPersistentStoreResult

例如,可能是以下方法(抓抓)

// somewhere in View declaration
@State private var refreshingID = UUID()

...
// somewhere in presenting fetch results
ForEach(fetchedResults) { item in
    ...
}.id(refreshingID) // < unique id of fetched results

...

// somewhere in bulk delete 
try context.save() // < better to save everything pending
try context.execute(deleteRequest)
context.reset() // < reset context
self.refreshingID = UUID() // < force refresh
2020-07-07