Post not yet marked as solved
Post marked as unsolved with 0 replies, 425 views
Use NSFetchedResultsController as the data source for UITableView. It is created with main context (persistentContainer.viewContext).Execute batch delete using background contextMerge 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