3
  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 codes:

let mainContext = persistentContainer.viewContext
let taskContext = persistentContainer.newBackgroundContext()
taskContext.perform {            
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(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? Please help. Thanks

1
  • try to do merging inside of mainContext.perform { ... } Mar 24, 2020 at 0:42

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.