ios - Swift:为什么从 NSManagedObject 继承会破坏我的属性?

标签 ios swift core-data nsmanagedobject

我是一个 Swift/IOS 新手,我根本无法理解 CoreData 的一些内容。

我有一个类,其中包含一些非可选属性,这些属性由指定的初始值设定项初始化。然后,如果我将该类设置为从 NSManagedObject 继承,那么我会突然收到错误

Stored property X requires an initial value or should be @NSManaged.

为什么 Swift 突然认为我的属性没有初始化,尽管它们显然已经初始化了?

此外,我读到@NSManaged“告诉编译器属性的存储和实现将由 CoreData 处理”,但这是什么意思?

任何答案将不胜感激..

最佳答案

我实际上昨天才读到这个。

Yes, it kinda really acts like @dynamic -- technically it might be identical even. Semantically there is a slight difference:

@dynamic says 'compiler, don't check if my properties are also implemented. There might be no code you can see but I guarantee it will work at runtime'

@NSManaged now says 'compiler, don't check those properties as I have Core Data to take care of the implementation - it will be there at runtime'

so you could even say: @NSManaged is syntactic sugar that is a more narrow version of dynamic :)

取自此question

Swift 的一大插入力是使语言变得极其安全,就像在本例中一样,检查属性是否在编译时实现。如果我理解正确的话,CoreData 不太符合这些编译时检查,因此添加 @NSManaged 让编译器知道变量将被处理。

来自Apple :

You use the @NSManaged attribute to inform the Swift compiler that Core Data provides the storage and implementation of a declaration at runtime.

关于ios - Swift:为什么从 NSManagedObject 继承会破坏我的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39042316/

相关文章:

ios - 线程 1 信号 SIGABRT 无法加载 Main.Storyboard

ios - 将 24 格式的时间转换为 12 格式

ios - 核心数据-根据应用程序版本不同的数据

ios - 我如何对核心数据迁移进行单元测试?

iphone - UItextView 阿拉伯文本右对齐

ios - 如何在 AsyncDisplayKit 中设置节点布局

ios - UITableViewCell 在关闭模态呈现的 ViewController 后不反射(reflect)更改

ios - coredata 中一列所有值的总和

ios - Swift:如何在 UIViewController 子类中初始化一个 let 常量

ios - @IBAction 只是 Swift 中的一种语法,还是 @Something 在 Swift 中意味着特定的事物?