- Use
as the data source forNSFetchedResultsController
. It is created with main context (UITableView
).persistentContainer.viewContext
- Execute batch delete using background context
- Merge changes into main context to update UI. (This is the problem. It freezes main thread).
Here are the related codes:
let mainContext = persistentContainer.viewContext
let taskContext = persistentContainer.newBackgroundContext()
taskContext.performAndWait {
let fetchRequest = NSFetchRequest(entityName: "MyItem")
fetchRequest.includesPropertyValues = false
let batchDeleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
batchDeleteRequest.resultType = .resultTypeObjectIDs
do {
let result = try taskContext.execute(batchDeleteRequest) as? NSBatchDeleteResult
let objectIDArray = result?.result as? [NSManagedObjectID]
let changes = [NSDeletedObjectsKey : objectIDArray]
/****below line of codes is the problem, it blocks main thread****/
NSManagedObjectContext.mergeChanges(fromRemoteContextSave: changes as [AnyHashable : Any], into: [mainContext])
} catch {
print("Error batch delete items: \(error.localizedDescription)")
}
}
Is there any way to avoid blocking main thread in this situation? Thanks