如何在 Swift 5 中强制更新 CoreData 代码文件(属性 扩展)?

How to force update CoreData Codefiles (Property Extension) in Swift 5?

我对 CoreData 有点困惑。在我的 xcdatamodeld 中,我能够创建新属性并更改它们的一些内容,例如 它们是否可选 .

For example, I created a property for my entity and called it descrip, the type is a String and I checked the Optional Field.

在其他时候,我尝试创建该实体的新对象并将其安全保存到 CoreData:

let newEntity = Entity(context: context)
newEntity.name = name
newEntity.descrip = descrip // descrip is an optional String
newEntity.filename = filename

我收到以下错误消息:Value of optional type 'String?' must be unwrapped to a value of type 'String'

Then, I tried to create the NSManagedObjectSubclasses for my Entity. I discovered, that while all properties have been added and the type of all is set correctly, the ? indicating the Optionality of the property was messed up completely.

import Foundation
import CoreData


extension Entity {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<Entity> {
        return NSFetchRequest<Entity>(entityName: "Entity")
    }

    @NSManaged public var name: String? // Should not be optional and was set so in xcdatamodeld
    @NSManaged public var descrip: String // Should be optional and set to optional in xcdatamodeld
    @NSManaged public var filename: String
}

有没有办法强制更新这个代码文件?或者我如何使用可选字符串来填写我的新实体的可选值?

该作业中的错误不是 Core Data 问题,它是纯粹的 Swift。您已将 descrip 声明为 String,但您正在尝试分配 String? 值。这在 Swift 中是不合法的——你必须在将一个可选的分配给一个非可选的之前打开它。如果您不使用 Core Data,情况也是一样的。例如,这会产生相同的错误:

let foo: String? = "hello"
let bar: String = foo

数据模型和生成的代码之间的差异是因为 Swift 可选项和 Core Data 可选项是完全不同的东西。当您保存更改时,Core Data 只关心某些内容是否可选。 Swift 关心某事是否一直是可选的。这是不同的,因为 Core Data 在 Swift 存在之前已经存在了很长时间,所以它并不总是与 Swift 期望的相匹配。