Core Data inheritance vs no inheritance

2019-02-19 16:08发布

i'm having some issues with core data, so i hope that someone will be able to help me :)

First problem, i have a data model that looks like this :

 Entity P (A) <----> Entity R
  / | \
 / /\ \ 
/ / | \ \
C D E F G

All my entities inherit from the same entity "P" because they need a common attribute and a common relationship ("A" and "R")

The problem i am getting is that core data uses generates only one sqlite table for all the entities when you use inheritance. In my case it means that my database will have only 1 table for all the datas. I did some research and i saw that it creates performance issues (moreover all my entities attributes are transients and during willSave their values are aggregated+encrypted into one NSData stored in "A", so i won't be able to use predicate to filter and improve SELECT performances). So i decided to remove "P", and to add "A" into "C", "D"..., "G". The problem is with "R", because before i had only one inverse relationship in it, and now i need to create one each time i create a new kind of entity. So i would like to remove all the inverse relationships, is it possible? Sometimes i need to create managed object with a nil context, and i insert them into the context later, this is probably why the inverse relationship are not automatically set by core data if i set the non-inverse before the insertion in the MOC right ? Anyway i never need the inverse, so can i avoid defining them even if i get a warning ?

2nd problem, in specific situations i need to create a new "R" and to assign it to "C", "D",.., "G" during the MOC save. So i would like to use willSave but, i don't know if the created entity will be saved. If the MOC does a simple loop over the "insertedObjects" / "updatedObjects" / "deletedObjects", and for each object it calls willSave, does the save, and then calls didSave, it means that i'm going to modify the array on which it is iterating, and then it should crash no?

2条回答
Luminary・发光体
2楼-- · 2019-02-19 16:45

As you and I both independently found out the hard way, be very, very careful with entities which inherit from each other. I too found Core Data tends to make one giant table containing all the fields for the base entity and all entities which derive from it, so any given entity contains the fields for every potential entity from its furthest ancestor downwards. Very, very slow and expensive.

I highly recommend only having the entity classes themselves inherit from each other, and mirroring the properties of the base class in all entities instead, without any actual inheritance in the managed object model itself.

查看更多
老娘就宠你
3楼-- · 2019-02-19 16:47

Core data is not a wrapper around your sql tables. It deals with object graph and its persistence. SQLite store is just one way of persisting it. Check this up. Prevent Core Data From Combining Entities into One Table

查看更多
登录 后发表回答