我在使用NSBatchDeleteRequest後從NSFetchedResultsControllerDelegate獲取準確更新的問題,更改作爲更新類型而不是didChange委託方法的刪除類型。有沒有辦法讓更改作爲刪除來進入? (我有不同的方案來刪除vs更新)。使用NSFetchedResultsController w/NSBatchDeleteRequest
刪除請求: (使用調用者提供私有上下文中)在
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
您正在對父上下文執行刪除操作,並且您表示要使用提供的私有上下文進行刪除。 – ELKA
@ELKA抓取的結果控制器是使用父上下文創建的,父上下文也是上下文,其父是持久存儲的應該刪除記錄的上下文。 –
因此context.parent將是一個主NSManagedObjectContext,它與NSFetchedResultController的上下文相同。正確? – ELKA