CoreStore transaction.edit建议使用相同变量名称的注释可以防止我们滥用非事务实例

问题描述 投票:0回答:1

从文档中我发现了这段代码:

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

很快就建议我使用其中两个:

enter image description here

ios swift core-data corestore
1个回答
0
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.