I want to store an enum state for a managed object within CoreData
enum ObjStatus: Int16 {
case State1 = 0
case State2 = 1
case State3 = 3
}
cla
You can extract raw Int16
value with .rawValue
property of ObjStatus
.
// compare
obj.state == ObjStatus.State1.rawValue
// store
obj.state = ObjStatus.State1.rawValue
But you might want to implement stateEnum
accessor for it:
class StateFullManagedObject: NSManagedObject {
@NSManaged var state: Int16
var stateEnum:ObjStatus { // ↓ If self.state is invalid.
get { return ObjStatus(rawValue: self.state) ?? .State1 }
set { self.state = newValue.rawValue }
}
}
// compare
obj.stateEnum == .State1
// store
obj.stateEnum = .State1
// switch
switch obj.stateEnum {
case .State1:
//...
case .State2:
//...
case .State3:
//...
}
You can declare your enum as @objc. Then it all automagically works. Here's a snippet from a project I'm working on.
// Defined with @objc to allow it to be used with @NSManaged.
@objc enum AgeType: Int32
{
case Age = 0
case LifeExpectancy = 1
}
/// The age type, either Age or LifeExpectancy.
@NSManaged var ageType: AgeType
In the Core Data model, ageType is set to type Integer 32.