Best way to implement Enums with Core Data

前端 未结 9 1601
天命终不由人
天命终不由人 2020-11-28 17:55

What is the best way to bind Core Data entities to enum values so that I am able to assign a type property to the entity? In other words, I have an entity called Item<

9条回答
  •  爱一瞬间的悲伤
    2020-11-28 18:16

    I have done this a lot and find the following form to be useful:

    // accountType
    public var account:AccountType {
        get {
            willAccessValueForKey(Field.Account.rawValue)
            defer { didAccessValueForKey(Field.Account.rawValue) }
            return primitiveAccountType.flatMap { AccountType(rawValue: $0) } ?? .New }
        set {
            willChangeValueForKey(Field.Account.rawValue)
            defer { didChangeValueForKey(Field.Account.rawValue) }
            primitiveAccountType = newValue.rawValue }}
    @NSManaged private var primitiveAccountType: String?
    

    In this case, the enum is pretty simple:

    public enum AccountType: String {
        case New = "new"
        case Registered = "full"
    }
    

    and call it pedantic, but I use enums for field names, like this:

    public enum Field:String {
    
        case Account = "account"
    }
    

    Since this can get laborious for complex data models, I wrote a code generator that consumes the MOM / entities to spit out all the mappings. My inputs end up being a dictionary from Table/Row to Enum type. While I was at it, I also generated JSON serialization code. I've done this for very complex models and it has turned out to be a big time saver.

提交回复
热议问题