首页 > 解决方案 > CoreStore transaction.edit 建议使用相同变量名的注释可以防止我们误用非事务实例

问题描述

从文档中我找到了这段代码:

let jane: MyPersonEntity = // ...

CoreStore.perform(
    asynchronous: { (transaction) -> Void in
        // WRONG: jane.age = jane.age + 1
        // RIGHT:
        let jane = transaction.edit(jane)! // using the same variable name protects us from misusing the non-transaction instance
        jane.age = jane.age + 1
    },
    completion: { _ in }
)

不知道为什么我们需要这样做// using the same variable name protects us from misusing the non-transaction instance

迅速建议我使用其中两个:

在此处输入图像描述

标签: iosswiftcore-datacorestore

解决方案


该建议利用了 swift 具有的变量名阴影功能。

Xcode 自动完成功能仍会显示两个“jane”,因为另一个名称为 name 的也位于同一范围内,但永远不能使用 - 因为它是阴影的。你在那里选择什么并不重要。由于这个原因,它是处理事务对象的最安全方法,因为它可以防止您意外使用错误的对象。


推荐阅读