我是一个 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/