如何在核心数据中存储快速枚举? [英] How to store swift enum in core data?

查看:81
本文介绍了如何在核心数据中存储快速枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

推荐答案

另一种方法是使用原始函数。这样避免了必须定义两个变量。在模型编辑器中,卡被定义为Int。

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

编辑:

可以将重复部分移至NSManagedObject的扩展名上。

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

这篇关于如何在核心数据中存储快速枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆