title: How to save to managed object context in a background thread in Core Data
body: <p>I have an app which takes about a minute to set up, so when the user taps ‘Start New Game’ I want to show an activity spinner while data is loaded into Core Data.</p>
  
  <p>I understand I have to do this on a background thread so I can update the UI on the main thread, but I don’t know how to save the managed context in the background thread. Here is what I have so far:</p>
  
  <pre><code>func startNewGame() {
    initiateProgressIndicator() // start the spinner and 'please wait' message
  
    DispatchQueue.global(qos: .background).async {
      self.coreDataStack.importDefaultData() // set up the database for the new game
  
      DispatchQueue.main.async {
          stopProgressIndicator()
  
          // Transition to the next screen
          let vc: IntroViewController = self.storyboard?.instantiateViewController(withIdentifier: "IntroScreen") as! IntroViewController
          vc.rootVCReference = self
          vc.coreDataStack = self.coreDataStack
          self.present(vc, animated:true, completion:nil)
      }
  }
  </code></pre>
  
  <p>In importDefaultData() I need to save multiple times but it crashes when I try to do so. I understand now it's because I'm trying to access the main context from a background thread. Here is the basic structure of the function:</p>
  
  <pre><code>func importDefaultData() {
      // import data into Core Data here, code not shown for brevity
  
      saveContext()
  
      // import more data into Core Data here, code not shown for brevity
  
      saveContext()
  
      // import final data here
  
      saveContext()
  }
  </code></pre>
  
  <p>From what I have read I think I need to create another managed object context for the background thread, but I am unclear on how to go about this and how to fit it into my current code. I also do not know how to make sure the data is saved correctly before I move on to the next screen. I have no experience with multithreading so any help would be appreciated.</p>
  
  <p>Edit: regarding being marked as duplicate, the suggested topic is 8 years old and doesn't contain any answers. I was hoping for a more up to date answer with perhaps a brief code example in Swift.</p>