核心数据 |自动生成的 String 和 Date 属性是可选的,即使未在 swift 中标记

Core data | automatically generated String and Date attributes are optional even when not marked in swift

我注意到日期和字符串属性总是在 swift 中创建为自动生成的 类 中的可选属性,即使未选择可选属性也是如此。

同样,在 apple documentation 中,所有日期和字符串在示例

中都显示为可选

In Swift, you declare the properties using the @NSManaged keyword:

class MyManagedObject: NSManagedObject {

@NSManaged var title: String?

@NSManaged var date: NSDate?

}

目前正在使用 swift 3.2 我不希望某些字符串属性是非可选的。使其成为强制性的最佳方法是什么?

When the entities will be fetched from core data, some of the properties of that entity may not have any value associated with them and they will be nil. That is why it make sense to have the core data properties as an optional.

同样,例如,如果您尝试从 Swift 中的字典中获取任何键的值,该值始终是可选的,因为字典中可能有也可能没有该键。因此,每次任何 属性 可能为零时,将其设为可选。

两个选项

  • 编辑 MyManagedObject 使它们成为非可选的。这意味着您需要自己维护此 class 并在核心数据模型和 class
  • 中进行任何更改
  • 创建一个具有相同属性(您需要给它们新名称)但非可选的协议(或子 class),并在单独的扩展中实现此协议以获取和设置原始属性,然后使用这个协议而不是 MyManagedObject 在你的代码中。

如果您的数据模型稳定且不会发生太大变化,第一个选项可能是最好的。