我为demo project和demo video准备了一个问题。
我想知道如何正确使用transaction.edit
。
当前,如果您看一下我的demo project,有一个名为updateCompany
的函数,我在其中将员工添加到公司中:
func updateCompany(with company: Company, completion: @escaping (Result<Company, Error>) -> Void) {
CoreStore.perform(
asynchronous: { (transaction) -> Company in
let editCompany = transaction.edit(company)!
editCompany.name = company.name
if let unwrappedEmployees = company.employees {
for employee in unwrappedEmployees {
if let castedEmployee = employee as? Employee {
let editEmployee = transaction.edit(castedEmployee)!
editCompany.addToEmployees(editEmployee)
}
}
}
return editCompany
},
success: { (transactionCompany) in
guard let fetchedObject = CoreStore.fetchExisting(transactionCompany) else {
return
}
completion(.success(fetchedObject))
},
failure: { (error) in
completion(.failure(error))
})
,在这种情况下,所有记录都正确保存,一切正常。但是令我感到奇怪的是,transaction.edit
函数描述说它“返回指定的NSManagedObject
或CoreStoreObject
的可编辑代理。”
因此,作为该功能的首次用户,您怀疑实际上是NSManagedObject
的代理(在我的情况下,这是上面的company
实例)与许多员工的关系已经存在。作为该函数的首次用户,您可以编写下一个代码:
func updateCompany(with company: Company, completion: @escaping (Result<Company, Error>) -> Void) {
CoreStore.perform(
asynchronous: { (transaction) -> Company in
let editCompany = transaction.edit(company)!
// take a look print(editCompany.employees)
// suspect all employees are there, but they are not!
return editCompany
},
success: { (transactionCompany) in
guard let fetchedObject = CoreStore.fetchExisting(transactionCompany) else {
return
}
// WHICH IS MORE STRANGE all added employees are returned here from successful transaction
completion(.success(fetchedObject))
},
failure: { (error) in
completion(.failure(error))
})
当您意识到发生了一件奇怪的事时,我们打开documentation并说:
请勿更新不是通过创建或获取的实例 交易。如果您已经有对该对象的引用,请使用 事务的edit(...)方法来获取可编辑的代理实例 该对象
正如您从演示项目中看到的那样,我更新了NSSet
的{{1}},它们是在employees
外部获取的,但是我猜这是关于执行异步/同步{{ 1}},用于更新transaction
请纠正我使用transaction
的正确方法。