更新时间:2022-05-17 22:16:46
另一种方法是使用原始函数。这样避免了必须定义两个变量。在模型编辑器中,卡被定义为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)
}