title: Why does NSManagedObject not get inserted into a child NSManagedObjectContext when the context is initialised inline?
body: <p>I am using child <code>NSManagedObjectContext</code>s in my iOS app as a scratchpad. I am using an extension of <code>NSManagedObjectContext</code> to create child contexts, as follows:</p>
  
  <pre><code>extension NSManagedObjectContext {
      func childContext(concurrencyType: NSManagedObjectContextConcurrencyType = .mainQueueConcurrencyType) -&gt; NSManagedObjectContext {
          let childContext = NSManagedObjectContext(concurrencyType: concurrencyType)
          childContext.parent = self
          return childContext
      }
  }
  </code></pre>
  
  <p>I was experiencing repeated errors with the following message for one part of my app when inserting a new <code>NSManagedObject</code> into a new child context (created from the <code>viewContext</code> of a <code>NSPersistentContainer</code>):</p>
  
  <blockquote>
    <p>CoreData: error: Mutating a managed object after it has been removed from its context</p>
  </blockquote>
  
  <p>This was strange, as other parts of the app -- which also used child contexts -- worked fine. Eventually, I narrowed the cause down to a small difference in the way I am inserting the new <code>NSManagedObject</code> (of entity name "Book") into the new child context. The following works as expected:</p>
  
  <pre><code>let childContext = container.viewContext.childContext()
  let object1 = NSEntityDescription.insertNewObject(forEntityName: "Book", into: childContext)
  print(object1.managedObjectContext == nil)
  // prints "false"
  </code></pre>
  
  <p>However, if I create the child context inline (i.e. <strong>not assigned to a variable</strong>, the managed object is <strong>not</strong> inserted into the context):</p>
  
  <pre><code>let object2 = NSEntityDescription.insertNewObject(forEntityName: "Book", into: container.viewContext.childContext())
  print(object2.managedObjectContext == nil)
  // prints "true"
  </code></pre>
  
  <p>This seems odd to me and can't figure it out. Everything is running on the main thread. I've also created a <a href="https://gist.github.com/AndrewBennet/ec17965d3605efc61fb7453e301d5ad1" rel="nofollow noreferrer">Swift playground</a> reproducing this behaviour.</p>