如何在核心数据中存储swift枚举?

问题描述 投票:4回答:1

Swift允许您定义枚举,但核心数据不支持(开箱即用)如何保存它们。

我在互联网上看到的推荐解决方案(到目前为止使用)是使用私有变量:

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)! }
   }
 }

在下面的答案中给出了另一种解决方案。

swift core-data enums
1个回答
10
投票

另一种方法是使用原始函数。这避免了必须定义两个变量。在模型编辑器中,卡被定义为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)!
    }
   }
 }

编辑:

重复部分可以移动到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)
}
© www.soinside.com 2019 - 2024. All rights reserved.