Core Data entity inheritance --> limitations?

前端 未结 3 1491
一向
一向 2021-01-05 10:30

I thought I\'ll post this to the community. I am using coredata, and have two entities. Both entities have a hierarchical relationship. I am noticing quite a lot of duplic

3条回答
  •  一生所求
    2021-01-05 10:56

    I think it's a mistake to draw to close a parallel between entities and classes. While very similar they do have some important differences.

    The most important difference is that entities don't have code like a class would so when you have entities with duplicate attributes, your not adding a lot of extra coding and potential for introducing bugs.

    A lot of people believe that class inheritance must parallel entity inheritance. It does not. As a long as a class descends from NSManagedObject and responds to the right key-value messages for the entity it represents, the class can have many merry adventures in it's inheritance that are not reflected in the entities inheritance. E.g. It's fairly common to create a custom base class right below NSManagedObject and the have all the subsequent managed object subclasses inherit from that regardless of their entities.

    I think the only time that entity inheritance is absolutely required is when you need different entities to show up in the same relationship. E.g:

    Owner{
      vehical<-->Vehical.owner
    }
    
    Vehical(abstract){
      owner<-->Owner.vehical
    }
    
    Motocycle:Vehical{ 
    
    }
    
    Car:Vehical{
    
    }
    

    Now the Owner.vehical can hold either a Motocycle object or a Car object. Note that the managed object class inheritance for Motocycle and Car don't have to be same. You could have something like Motocycle:TwoWheeled:NSManagedObject and Car:FourWheeled:NSManagedObject and everything would work fine.

    In the end, entities are just instructions to context to tell it how the object graph fits together. As long as your entity arrangement makes that happen, you have a lot flexibility in the design details, quite a bit more than you would have in an analogous situation with classes.

提交回复
热议问题