I defined a global enum named MyEnum:
enum MyEnum: Int{
case year = 100, month, week, day
}
Purpose is to stored this enum as an attribute of my entity(I declare this enum attribute as transformable in xcdatamodel file):
After Creating NSManagedObject Subclass, In +CoreDataProperties.swift, I tried to changed the
@NSManaged public var myEnum: NSObject
to
@NSManaged public var myEnum: MyEnum
But when performing saveContext(), error still occurred. I just begin to learn and have no way about how to do next
so what extra work should I do to stored my enum as an attribute for my entity?
Please use swift, thanks for any help
We generally store enumerations as strings or as integers into database. It really depends on the case which to use but consider you have something like
@NSManaged public var myEnumAsInteger: Int
Then to save it all you do is:
myObject.myEnumAsInteger = enumValue.rawValue
and to read it:
enumValue = MyEnum(rawValue: myObject.myEnumAsInteger)
Or you can just create another property and override getter, setter as so:
@NSManaged public var myEnumAsInteger: Int
var myEnum: MyEnum {
set {
self.myEnumAsInteger = newValue.rawValue
}
get {
return MyEnum(rawValue: self.myEnumAsInteger) ?? .year // Or whatever the default is
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With