Best way to implement Enums with Core Data

前端 未结 9 1544
天命终不由人
天命终不由人 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:28

    Since enums are backed by a standard short you could also not use the NSNumber wrapper and set the property directly as a scalar value. Make sure to set the data type in the core data model as "Integer 32".

    MyEntity.h

    typedef enum {
    kEnumThing, /* 0 is implied */
    kEnumWidget, /* 1 is implied */
    } MyThingAMaBobs;
    
    @interface myEntity : NSManagedObject
    
    @property (nonatomic) int32_t coreDataEnumStorage;
    

    Elsewhere in code

    myEntityInstance.coreDataEnumStorage = kEnumThing;
    

    Or parsing from a JSON string or loading from a file

    myEntityInstance.coreDataEnumStorage = [myStringOfAnInteger intValue];
    
    0 讨论(0)
  • 2020-11-28 18:33

    An alternative approach I'm considering is not to declare an enum at all, but to instead declare the values as category methods on NSNumber.

    0 讨论(0)
  • 2020-11-28 18:35

    I set the attribute type as 16 bit integer then use this:

    #import <CoreData/CoreData.h>
    
    enum {
        LDDirtyTypeRecord = 0,
        LDDirtyTypeAttachment
    };
    typedef int16_t LDDirtyType;
    
    enum {
        LDDirtyActionInsert = 0,
        LDDirtyActionDelete
    };
    typedef int16_t LDDirtyAction;
    
    
    @interface LDDirty : NSManagedObject
    
    @property (nonatomic, strong) NSString* identifier;
    @property (nonatomic) LDDirtyType type;
    @property (nonatomic) LDDirtyAction action;
    
    @end
    

    ...

    #import "LDDirty.h"
    
    @implementation LDDirty
    
    @dynamic identifier;
    @dynamic type;
    @dynamic action;
    
    @end
    
    0 讨论(0)
提交回复
热议问题