So, I’m just getting to really enjoy Core Data, and have started integrating it into an app I’m working on. However, I have encountered a problem for which I see no obvious solution, which is making me feel like maybe Core Data’s not the right tool for the job. Here’s the situation: I have a tree of Nodes, each of which may or may not have children. There may be arbitrarily many root Nodes. I have put together the data model using to-many relationships (from Node to Nodes) with to-one inverse relationships. All that is fine.
Now, each Node also has a to-many relationship to Records, which also have an inverse to-one relationship back to the Node. What I want to do is find all Records which have a specific boolean attribute set to true, and are somewhere below a given Node. This was super easy before I was using Core Data — I just walk the tree. However, this is time consuming, and I was hoping that Core Data would give me a way to just make a fetch request which would grab all the Records I want quickly. I can see how to do it (semi) easily if I know the max depth I want to check, but what if I want to go all the way down? What if not all Nodes have children?
Should I just walk the tree as I was doing before?
Is NSFetchRequest even capable of performing such a task?
This isn’t a core data problem, but a graph problem. You have to do the same searching. However, CoreData can allow you to fault in the objects. So, you have several options, two of which are
1) Walk the tree. You should be able to use the exact same algorithm you were using with the in-memory tree. CoreData should just fault in the objects. Unless you have an extremely deep tree, you should be fine.
2) Encode the parent relationship in each record. A fair amount of updating when the tree is updated, but fetches will be quicker.
The following can be turned into a NSCompoundPredicate and assigned as the fetch predicate… Docs say it works on CoreData, but not for sqllite – try it.