Skip to content

Instantly share code, notes, and snippets.

@AndrewBennet
Created February 26, 2018 08:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AndrewBennet/ec17965d3605efc61fb7453e301d5ad1 to your computer and use it in GitHub Desktop.
Save AndrewBennet/ec17965d3605efc61fb7453e301d5ad1 to your computer and use it in GitHub Desktop.
Why does NSManagedObject not get inserted into a child NSManagedObjectContext when the context initialised inline?
import CoreData
import PlaygroundSupport
extension NSManagedObjectContext {
func childContext(concurrencyType: NSManagedObjectContextConcurrencyType = .mainQueueConcurrencyType) -> NSManagedObjectContext {
let childContext = NSManagedObjectContext(concurrencyType: concurrencyType)
childContext.parent = self
return childContext
}
}
// Requires a momd called "books" be added to the Resources directory of the playground
let container = NSPersistentContainer(name: "books")
container.loadPersistentStores{ description,error in
let childContext = container.viewContext.childContext()
let obj1 = NSEntityDescription.insertNewObject(forEntityName: "Book", into: childContext)
print(obj1.managedObjectContext == nil)
let obj2 = NSEntityDescription.insertNewObject(forEntityName: "Book", into: container.viewContext.childContext())
print(obj2.managedObjectContext == nil) // prints true: why?
}
PlaygroundPage.current.needsIndefiniteExecution = true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment