How to store swift enum in core data?

霸气de小男生 提交于 2020-07-18 05:31:08

问题


Swift allows you to define enum but core data doesn't support (out of the box) how to save them.

The recommended solution I have seen on the internet (and used thus far) is to use a private variable:

class ManagedObjectSubClass : NSManagedObject
{
  enum Cards : Int
  {
    case Diamonds, Hearts
  }
   @nsmanaged var cardRaw: Int

   var card : Cards {
     set { self.cardRaw = newValue.rawValue }
     get { return Cards(RawValue:cardRaw)! }
   }
 }

An alternate solution is given in the answer below.


回答1:


Another approach is to use the primitive functions. This avoid having to define two variables. In the model editor card is defined as an Int.

class ManagedObjectSubClass : NSManagedObject
{
  enum Cards : Int
  {
    case Diamonds, Hearts
  }

   var card : Cards {
     set { 
        let primitiveValue = newValue.rawValue
        self.willChangeValueForKey("card")
        self.setPrimitiveValue(primitiveValue, forKey: "card")
        self.didChangeValueForKey("card")
     }
     get { 
        self.willAccessValueForKey("card")
        let result = self.primitiveValueForKey("card") as! Int
        self.didAccessValueForKey("card")
        return Cards(rawValue:result)!
    }
   }
 }

edit:

The repetitive part can be moved to an extension on NSManagedObject.

func setRawValue<ValueType: RawRepresentable>(value: ValueType, forKey key: String)
{
    self.willChangeValueForKey(key)
    self.setPrimitiveValue(value.rawValue as? AnyObject, forKey: key)
    self.didChangeValueForKey(key)
}

func rawValueForKey<ValueType: RawRepresentable>(key: String) -> ValueType?
{
    self.willAccessValueForKey(key)
    let result = self.primitiveValueForKey(key) as! ValueType.RawValue
    self.didAccessValueForKey(key)
    return ValueType(rawValue:result)
}


来源:https://stackoverflow.com/questions/35378401/how-to-store-swift-enum-in-core-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!