Search code examples
swiftxcodecore-datadatamodel

Swift: Core Data model relationships to mirror API view model


I am trying to create a core data model but as a Core Data newbie, I'm unclear as to how to use relationships for my purpose.

Essentially I need to store an object that looks something like this class (there are more values required but this is the structure), the purpose being that the below is essentially the model I used when fetching data from a specific API, but I am trying to implement offline functionality so need essentially mirror this model in core data):

class SheetModel {

     uplift: String
     date: String
     time: String
     density: String
     discrepancy: String
     id: String

  Mass {
      unit:  String
      display: String
      unitName: String
   }
  Density {
      unit:  String
      display: String
      unitName: String
   }
  Volume {
      unit:  String
      display: String
      unitName: String
   }
 }

I am unclear how to create a data model to allow me to store something like the above. My (poor) attempt is as follows:

enter image description here

I know that the relationships here are totally wrong but can't figure out what I should be doing here. So obviously the Volume, Mass, Density entities all should belong to the same NSManagedObject that is storing the uplift, date etc. attributes.


Solution

  • You are misunderstanding what "parent entity" means in CoreData! That's how you specify inheritance not containment. So if you had a Circle entity, it would be appropriate for its parent entity to be a more generic Shape entity.

    You need to clear out those parent entity settings and instead add "relationships" to your entities. Each of your mass/density/volume entities should have a relationship where the destination is StoredRefuelSheet the delete rule is Nullify and the type is To One. That means you can't share a mass between two sheets and you can delete a mass without deleting its owning sheet. You should also set up an inverse relationship, so the sheet would have a mass relationship with destination Mass, delete rule Cascade, and type To One. That means if you delete a sheet its contained mass is also deleted.

    After that, you do actually have an opportunity to use parent entities: your mass/density/volume entities all have the same fields! That would be a good use case for an abstract parent entity that specifies the common fields so you don't have to duplicate them.