2016-02-13 131 views
3

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)! } 
    } 
} 

另一種解決方案在下面的答案給出。

回答

7

另一種方法是使用原始函數。這避免了必須定義兩個變量。在模型編輯器卡中定義爲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) 
}