加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 04:49:18 所属栏目:百科 来源:网络整理
导读:Swift允许您定义枚举,但核心数据不支持(开箱即用)如何保存它们. 我在互联网上看到的推荐解决方案(到目前为止使用)是使用私有变量: class ManagedObjectSubClass : NSManagedObject{ enum Cards : Int { case Diamonds,Hearts } @nsmanaged var cardRaw: Int
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)! }
   }
 }

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

解决方法

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读