title: How does Core data concurrency work with multithreading in Swift 3?
body: <p>In my program, it uses both of</p>
  
  <pre><code>DispatchQueue.global(qos: .background)
  </code></pre>
  
  <p>and </p>
  
  <pre><code>self.concurrentQueue.sync(flags: .barrier)
  </code></pre>
  
  <p>to deal with the background multithread issues. </p>
  
  <p>It is swift 3 so I use the latest way to get the childContext:</p>
  
  <pre><code>lazy var context: NSManagedObjectContext = {
      return (UIApplication.shared.delegate as! AppDelegate).persistentContainer.newBackgroundContext()
  }()
  </code></pre>
  
  <p>I also enable <code>-com.apple.CoreData.ConcurrencyDebug 1</code> to debug</p>
  
  <p>Then the problem occurs:</p>
  
  <p>1, When there's an API call and in the callback block (background thread), I need to fetch the core data, edit, then save. I tried to use self.context from the code above to call <code>performBlockAndWait</code> and do <code>save</code> inside of this block. The whole process goes fine but when I try to access my result outside of this block but inside of the callback block, the error occurs. I have also tried to get the objectId and <code>getObjectById</code> by both self.context and self.context.parent and the error occurs on this line. What did I do wrong and how should I do this? since I need to use the result everywhere in many different thread (not context).</p>
  
  <p>2, I read a post says that I need one context per thread, then in my case, how do I determine which exact thread it is if it's a call back from API call and do I really need to do this?</p>
  
  <p>3, You might ask that why do I need a privateConcurrentType, because my program has things need to be running in background thread so that it has to do it this way, (read from other post), is this right?</p>
  
  <p>4, Even in my question 1, get object by passing objectId to different Context still not working in my case. Let's assume this is the proper way. How am I gonna manage passing so many objectID throughout my entire program in different thread without being super messy? To me this sounds crazy but I suppose there's a much cleaner and easier way to deal with this.</p>
  
  <p>5, I have read many posts some are pretty old (before swift 3), they have to   do <code>childContext.save</code> then <code>parentContext.save</code>, but since I use the code above (swift 3 only). It seems that I can do childContext.save only to make it work? Am I right?</p>