One of my model objects has an enum property. To save it to CoreData, I used an NSNumber object.
However, I would like to access it as an enumeration type in a convenient way. What is the best practice to achieve this?
So far I have gone with the following code.
in MyObject.h
typedef enum _ABType {
ABTypeUnknown,
ABTypeValue1,
...
ABTypeValueN
} ABType;
@interface MyObject : NSManagedObject
@property (nonatomic, retain) NSNumber * myPersistentEnum;
@property (nonatomic) ABType myConvenientEnum;
in MyObject.m
@dynamic myPersistentEnum;
- (BOOL)isValidEnumValue {
if (self.myPersistentEnum) {
int intValue = [self.type intValue];
if (intValue >= ABTypeValue1 && intValue <= ABTypeValueN) {
return YES;
}
}
ELog(@"Undefined enumValue %@", self.myPersistentEnum);
return NO;
}
- (ABType)myConvenientEnum {
if ([self isValidEnumValue]) {
return [self.type intValue];
}
return ABTypeUnknown;
}
- (void)setMyConvenientEnum:(ABType)enumValue {
NSNumber *oldValue = [self.myPersistentEnum retain];
self.myPersistentEnum = [NSNumber numberWithInt:enumValue];
if ([self isValidEnumValue]) {
[oldValue release];
} else {
self.myPersistentEnum = oldValue;
[oldValue release];
}
}
My questions:
- Is there something wrong in the code above?
- Is the
intcorrect type used when converting an enumeration to NSNumber? (NSNumber does not provide a method -(enum)enumValue;) - Could you leave the validation aspect to validate the CoreData model at runtime?
- [NEW] How can I make it clear to other developers that I need to use a convenient property, not the NSNumber property?