I’m considering using Core Data for an app I’m writing. However, after reading the docs I’m unsure how to model a particular relationship. Here’s the basics:
I have an Entity called “ProjectFile” that has some basic string properties. (One of those is a path to a file on disk — call it “File X” — that my app is going to manipulate.) However, when the app manipulates file X, it may also need to manipulate OTHER files — fileY and fileZ.
FileY and FileZ, like fileX, will be “ProjectFile” entities. So I need a way to tell Core Data “FileY and FileZ are associated with FileX.” To do that, I created a relationship on the “ProjectFile” entity called “linkedFiles” and set the destination to “ProjectFile” and the inverse to “linkedFiles”. I then set this as a “to-many” relationship, as each “ProjectFile” may have multiple linked files.
This seems recursive to me and I’m not sure I’ve done it correctly. The “linked” files (fileY and fileZ) need to exist on their own, just as fileX does. I need to be able to “delete” them from the “linkedFiles” relationship but still have them exist separately, if that makes sense. Essentially, I just need a weak relationship between separate objects in my model.
Have I done this correctly, or am I missing something? Thanks!
So, you have a data model that looks something like this:
This will work because (1) Core Data relationships have directionality/cardinality and (2) each object is unique. Where you can get into trouble is with delete rules. You pretty much have to use
No ActionorNullifyin this circumstance or risk setting off a cascade delete. That in turn runs the risk creatingorphanedobjects that have no relationships and are hard to find and remove in the object graph.A better model would encode more information in the relationships themselves. It appears that the real-world file objects you are modeling have two separate relationships to other file objects: (1) Each instance has other instances that it manipulates and (2) each instance has other instances that manipulate it. So, your model should reflect that:
This makes explicit the type relationship between the objects and lets you quickly and easily get the right objects for any particular operation. You can use
Nullifyon one relationship without orphaning the object on the other.Although it isn’t immediately obvious, relationships aren’t just lines on a graphical model, they are actual live objects that can carry a lot of information. You need to design with this in mind.