Can CoreData handle polymorphic subclasses?
I have a CoreData model (managed object) called Item:
@interface Item : NSManagedObject {
NSString * type;
}
@property (retain) NSString * type;
@end
I also have two subclasses of Item:
@interface Circle : Item
@end
@interface Square : Item
@end
I track the subcl开发者_如何学Goass of the item by the type
property.
When I fetch my Items
, I get back an array of Items. But I want to be able to dynamically typecast the items according to their type
.
Does CoreData support this natively? If not, is there a way to dynamically typecase each Item
?
I can get the class that I want to cast the Item
as like:
Item * item = ...;
id klass = NSClassFromString(item.type);
I just don't know how I can cast item
as type klass
.
Yes it's built in. You don't have to do it manually. You don't even have to put the type
entry yourself.
In Objective-C there's the concept of superclass / subclass . Correspondingly, in Core Data, there's the concept of parent entity / child entity. This can be specified in the model file.
In the Core Data modeler, create two entities Circle
and Square
by inheriting your Item
entity. You can specify the parent
of the entity in the modeler. Then, in the modeler, specify the custom class Circle
for your entity Circle
, the class Square
for the entity Square
.
Then, when you fetch the managed object from the database, the correct class is automatically assigned. Read the documentation of the modeler.
Again, everything can be done in the modeler, without your writing anything.
精彩评论