I'm using MagicalRecord and am trying to create an entity in a background thread then use it in the main thread. This is the code I have:
var localRecipe: Recipe?
MagicalRecord.save({ (localContext : NSManagedObjectContext!) in
localRecipe = Recipe.createEntity()
localRecipe?.name = "HiHi"
}, completion: { (success : Bool, error : Error?) in
print(localRecipe?.name)
let recipe = localRecipe?.mr_(in: NSManagedObjectContext.mr_default())
print(recipe?.name)
})
When I try to retrieve localRecipe in the main context the object does not exist in the persistent store. What am I doing wrong here?
I believe Recipe.createEntity()
is creating the Recipe
in the default context.
You should be using the localContext
provided in the block to create your Recipe
entity. e.g:
localRecipe = Recipe.createEntityInContext(localContext)
Then when the localContext
is saved it should be merged into the main context, NSManagedObjectContext.mr_default()