Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 subclass 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.

like image 608
Aaron Wheeler Avatar asked Sep 30 '10 00:09

Aaron Wheeler


1 Answers

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.

like image 116
Yuji Avatar answered Nov 16 '22 03:11

Yuji