NSManagedObjectContext.mergeChanges froze main thread

  1. Use
    NSFetchedResultsController
    as the data source for
    UITableView
    . It is created with main context (
    persistentContainer.viewContext
    ).
  2. Execute batch delete using background context
  3. 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