gpt4 book ai didi

ios - 使用带 NSBatchDeleteRequest 的 NSFetchedResultsController

转载 作者:搜寻专家 更新时间:2023-10-31 22:01:55 24 4
gpt4 key购买 nike

我在使用 NSBatchDeleteRequest 后从 NSFetchedResultsControllerDelegate 获取准确更新时遇到问题,更改作为更新类型而不是 didChange 委托(delegate)方法上的删除类型出现。有没有办法让更改以删除的形式出现? (对于删除和更新,我有不同的方案)。

删除请求:(使用调用者提供的私有(private)上下文)

fileprivate class func deletePeopleWith(ids: Set<Int>, usingContext context: NSManagedObjectContext) {

let fr: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "Person")

var predicates: [NSPredicate] = []
ids.forEach {

predicates.append(NSPredicate(format: "id = %ld", $0))
}

fr.predicate = NSCompoundPredicate(orPredicateWithSubpredicates: predicates)

let dr = NSBatchDeleteRequest(fetchRequest: fr)
dr.affectedStores = context.parent?.persistentStoreCoordinator?.persistentStores

do {

try context.parent?.execute(dr)
context.parent?.refreshAllObjects()
print("Deleting person")

} catch let error as NSError {

let desc = "Could not delete person with batch delete request, with error: \(error.localizedDescription)"
debugPrint(desc)
}

}

结果:

func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {

DispatchQueue.main.async {

let changeDesc = "Have change with indexPath of: \(indexPath), new index path of: \(newIndexPath) for object: \(anObject)"
var changeType = ""
switch type {

case .delete:
changeType = "delete"

case .insert:
changeType = "insert"

case .move:
changeType = "move"

case .update:
changeType = "update"

}

print(changeDesc)
print(changeType)
}

}

打印:

Have change with indexPath of: Optional([0, 0]), new index path of: Optional([0, 0]) for object: *my core data object*
update

最佳答案

来自 Apple 的 documentation :

Batch deletes run faster than deleting the Core Data entities yourself in code because they operate in the persistent store itself, at the SQL level. As part of this difference, the changes enacted on the persistent store are not reflected in the objects that are currently in memory.

After a batch delete has been executed, remove any objects in memory that have been deleted from the persistent store.

参见 Updating Your Application After Execution用于处理被 NSBatchDeleteRequest 删除的对象的部分。

关于ios - 使用带 NSBatchDeleteRequest 的 NSFetchedResultsController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40575339/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com