views:

258

answers:

2

I am building a Core Data model and one of my classes needs to have a variable that can best be implemented as a typedef. Right now I am implementing it as a string variable that takes three possible values, but of course this is not robust.

Is there a way to implement this in the Core Data model?

+1  A: 

I've looked at using an enum typedef recently, and stored it as an NSNumber in Core Data. I implemented my own subclass of NSManagedObject and created a property for my type. In the accessors I then converted to and from NSNumber:

- (MyTypedef)type {
    NSNumber *value = [self primitiveValueForKey:@"type"];
    return [value integerValue];
}

- (void)setType:(MyTypedef)aType {
    NSNumber *value = [NSNumber numberWithInteger:aType];
    [self setPrimitiveValue:value forKey:@"type"];
}

In the end I didn't go with this solution, but it worked fine for me then (on the iPhone). Not sure if the above code is absolutely correct - I justed typed it into this browser window.

There is probably more work required if you want to use KVO etc. and you might want to do some error checking in the accessor method to check whether what you get back in the NSNumber is actually valid in the enum.

Thomas Müller
+1  A: 

You can have integer attribute and transcient attribute of undefinied type which is initialized depending on the integer attribute value?

Eimantas