我正在尝试实现一个核心数据模型,该模型可以有效地镜像我从特定API中提取信息时使用的视图模型。我大部分内容都经过排序,但都在为一种属性而苦苦挣扎。有问题的属性是:
enum UnitType: String, Codable {
case psi
case kPa
case litre
case usg = "gallon"
case kmph = "km/hour"
case mph = "miles/hour"
case celsius
case fahrenheit
case kgpmcubed = "kgpercubicmeter"
case lbspusg = "lbsperusg"
case lbspftcubed = "lbspercubicfeet"
case apidensity
case kg = "kilogram"
case lbs = "pound"
}
我需要能够在此处设置枚举值,因为视图控制器使用此UnitType属性基于此枚举进行各种计算。如何使用核心数据创建枚举?本质上,我需要能够像这样设置此值:
MyEntity.unitType = viewModel.UnitType
您无法在enum
中存储CoreData
类型,但是可以存储rawValue
。由于您的枚举的rawValue为String
类型,因此可以存储它的rawValue并使用枚举的enum
方法转换回init
,如下所示:
coreDataModel.unitType = viewModel.unitType.rawValue
和:
viewModel.unitType = UnitType(rawValue: coreDataModel.unitType)
注:从rawValue
转换为enum
类型时,它是可选的,因为String
可以是任何东西,并且不能与case
中提供的任何enum
匹配。因此,将需要提供default
值。
很遗憾,您无法将枚举保存在CoreData
中。
您可以在模型中具有String
变量:
class MyEntity: NSManagedObject {
@NSManaged public var unitType: String
}
然后您可以随时将其转换为您的UnitType。
myEntity.unitType = viewModel.UnitType.rawValue
viewModel.unitType = UnitType(rawValue: myEntity.unitType)!