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

Creating an entity in a background thread in CoreData

我正在使用 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() 正在默认上下文中创建 Recipe

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

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