views:

26

answers:

1

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.

+1  A: 

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.

Yuji
Thanks! It's frustrating not knowing what to search for. No wonder "subclass" and "polymorphic" weren't returning results! Just as a note, the **Core Data Programming Guide: Managed Object Models** has much more in-depth information under the sections **Entity Inheritance** and **Abstract Entities**http://developer.apple.com/library/mac/#documentation/cocoa/conceptual/CoreData/Articles/cdMOM.html
Aaron Wheeler