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)
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句