Created
February 26, 2018 08:01
-
-
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?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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