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)!
}
}
}
edit:
重复的部分可以移至 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)
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)