Swift: Storing states in CoreData with enums

后端 未结 2 1756
灰色年华
灰色年华 2020-11-30 23:36

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         


        
相关标签:
2条回答
  • 2020-12-01 00:08

    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:
        //...
    }
    
    0 讨论(0)
  • 2020-12-01 00:11

    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.

    0 讨论(0)
提交回复
热议问题