Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abstract entities and inheritance in Core Data

I have a data model for Formula 1 races with 3 entities:

  • RacingActor: Abstract entity
  • Pilot: inherits from RacingActor
  • Team: inherits from RacingActor

enter image description here

If I generate NSManagedObject subclasses to represent these entities, the code generated doesn't represent at all this design:

  • Everything inherits from NSManagedObject
  • Nothing prevents me from instantiating RacingActor
  • The team property in Pilot is of type NSManagedObject instead of Team

Is this the expected behaviour? Am I supposed to fix the code generated by Xcode? Am I missing something?

BTW, I'm using Xcode 4.3.3

like image 439
cfischer Avatar asked Jul 08 '12 17:07

cfischer


People also ask

What is an entity in Core Data?

An entity describes an object, including its name, attributes, and relationships. Create an entity for each of your app's objects.

What is abstract entity in Java?

An abstract class may be declared an entity by decorating the class with @Entity. Abstract entities are like concrete entities but cannot be instantiated.

How do I use Core Data?

Use Core Data to save your application's permanent data for offline use, to cache temporary data, and to add undo functionality to your app on a single device. To sync data across multiple devices in a single iCloud account, Core Data automatically mirrors your schema to a CloudKit container.

What is Nsmanagedobjectmodel in Swift?

Mapping between your managed objects and a database or file-based schema for object persistence.


1 Answers

Core Data at the core is an object relational mapping library. Long time ago it was called Entreprise Object Framework, part of WebObjects.

So yes, the base object for any persistant object managed by Core Data is NSManagedObject, and you can do whatever you want with them.

In your example, Team and Pilot will share a common table, and you'll be able to use queries to retrieve Teams and Pilots at once. That's the idea.

The Objective-C inheritance tree (if you use custom classes) can mirror the model you defined, but it doesn't need to. You can create a custom RacingActor class, use it as a base class for custom Team and Pilot classes, or you can tell the model to use RacingActor for Team and Pilot objects. You can even define a completely unrelated base class (provided NSManagedObject is a parent, directly or indirectly) for Team and / or Pilot if you want to.

You are then free to implement the specific behaviors you need in your business logic, either in controllers or in custom data classes.

like image 78
fabrice truillot de chambrier Avatar answered Sep 29 '22 14:09

fabrice truillot de chambrier