开发者

Core Data inheritance: Is it OK to do this?

开发者 https://www.devze.com 2023-02-01 06:07 出处:网络
Example: I have an Entity called Car which is abstract. Then there are two child entities Cabriolet and Pickup.

Example: I have an Entity called Car which is abstract. Then there are two child entities Cabriolet and Pickup.

Now I have an Entity called Driver which has a Relationship called currentCar 1..1 to the Entity Car开发者_JAVA技巧. So I can assign either a Cabriolet or a Pickup to any driver's currentCar property. Then I would need to introspect the object to find out at runtime if I have a Cabriolet or Pickup when I get the currentCar from the driver. Is this a valid design in Core Data?


I don't see why this wouldn't work on a technical level, but it does violates OOP polymorphism.

Why do you need to know if the type of car? Would you be able to define the methods on the abstract superclass (Car) and override them as appropriate in the the subclasses (Cabriolet and Pickup)? Could you refactor the car hierarchy so that the attributes of the subclasses become more general and move them to attributes of Car, thus removing the need for the subclasses?

I had trouble with NSFetchResultsController when fetching objects derived from a common superclass. (The returned objects can only be sorted/grouped by an attribute of the entity. The class type is not an attribute so cannot be used to sort/group the entities. My solution/hack was to a type attribute to the superclass - ugly, but it worked.)

0

精彩评论

暂无评论...
验证码 换一张
取 消