我正在尝试实现一个核心数据模型,该模型可以有效地镜像我从特定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
答案 0 :(得分:1)
您不能在enum
中存储CoreData
类型,但是可以存储rawValue
。由于您的枚举的rawValue类型为String
,因此您可以存储它的rawValue并使用枚举的enum
方法转换回init
,如下所示:
coreDataModel.unitType = viewModel.unitType.rawValue
和:
viewModel.unitType = UnitType(rawValue: coreDataModel.unitType)
注意:当从rawValue
转换为enum
类型时,它是可选的,因为String
可以是任何东西,并且不能与case
。因此,将需要提供一个enum
值。
答案 1 :(得分:1)
很遗憾,您无法在downloadItem({ url, name }) {
axios
.get(url, { responseType: 'blob' })
.then((response) => {
const blob = new Blob([response.data], { type: response.data.type });
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = name;
link.click();
URL.revokeObjectURL(link.href);
})
.catch(console.error);
},
中保存枚举。
您的模型中可以有一个CoreData
变量:
String
然后您可以随时将其转换为您的UnitType。
class MyEntity: NSManagedObject {
@NSManaged public var unitType: String
}