【问题标题】:How to store swift enum in core data?如何将快速枚举存储在核心数据中?
【发布时间】:2016-02-13 09:51:09
【问题描述】:

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】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-20
      • 1970-01-01
      • 1970-01-01
      • 2011-11-21
      相关资源
      最近更新 更多