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

标签 ios swift core-data corestore

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

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

不确定为什么我们需要这样做//使用相同的变量名可以防止我们滥用非事务实例

swift 建议我使用其中两个:

enter image description here

最佳答案

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

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

关于ios - CoreStore transaction.edit 建议使用相同变量名的注释可以防止我们误用非事务实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55920699/

相关文章:

ios - Swift - 解析结果现在总是空的但以前不是?仍然可以发布对象但不能通过查询获取?

swift - 无法对 Swift 数组进行排序

python - 苹果推送通知不适用于 python

ios - 为什么 U+E006 (  ) 在 iOS 上显示为 T 恤?

ios - 使用The Amazing Audio Engine时,传递给ABReceiverPortReceive的AudioBufferList与clientFormat不匹配

ios - 在 Swift 的 NSUserDefaults 中保存自定义类对象

ios - 在 Core Data 中,如何在 swift 4 中执行 `if exists update else insert`?

iphone - 应用程序运行时替换 Core Data sqlite 文件,数据不更新

ios - 存储的属性需要一个初始值或者应该是@NSManaged

ios - 是否有可能为 iOS 开发像 Google Courgette 这样的技术?