3

I have a data model relationship of Person - Children in Core Data. So for example, A Person can have children and his children can have children, and so his children's children can have children and so on.

How would I be able to fetch all the children, grand children and grand grand children using a predicate?

SleepNot
  • 2,982
  • 10
  • 43
  • 72

1 Answers1

1

If you have a Person object, thePerson, then to fetch their children you would use the following predicate:

NSPredicate(format:"parent == %@", thePerson)

To fetch their grandchildren, use:

NSPredicate(format:"parent.parent == %@", thePerson)

and for their great-grandchildren, use:

NSPredicate(format:"parent.parent.parent == %@", thePerson)

Combine those together:

NSPredicate(format:"parent == %@ OR parent.parent == %@ OR parent.parent.parent == %@", thePerson, thePerson, thePerson)
pbasdf
  • 21,386
  • 4
  • 43
  • 75
  • 1
    Thanks for the answer. And pardon me if I used a "fixed" example in my question. But what if I do not know the number of levels to get the outmost children. – SleepNot Aug 29 '17 at 09:18
  • I was afraid you might want that. I think you might need to change your model - but I will have to think through how best to change it. – pbasdf Aug 29 '17 at 09:27