Swift 在CoreData的后台线程中创建实体

Swift 在CoreData的后台线程中创建实体,swift,core-data,magicalrecord,Swift,Core Data,Magicalrecord,我正在使用MagicalRecord,试图在后台线程中创建一个实体,然后在主线程中使用它。这是我的代码: var localRecipe: Recipe? MagicalRecord.save({ (localContext : NSManagedObjectContext!) in localRecipe = Recipe.createEntity() localRecipe?.name = "HiHi" }, completion: { (success : Boo

我正在使用MagicalRecord,试图在后台线程中创建一个实体,然后在主线程中使用它。这是我的代码:

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)
})

当我尝试在主上下文中检索localRecipe时,持久存储中不存在该对象。我做错了什么?

我相信
Recipe.createEntity()
正在默认上下文中创建
配方

您应该使用块中提供的
localContext
来创建
Recipe
实体。例如:
localRecipe=Recipe.createEntityInContext(localContext)


然后,当保存
localContext
时,它应该合并到主上下文中,
NSManagedObjectContext.mr_default()

我不确定这是否是唯一的问题。让我知道你怎么样了,就是这样!谢谢,呜呼!没问题:)