如何在核心数据中存储快速枚举?
问题描述:
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)
}