Search code examples
iosswiftcore-datanspredicate

swift CoreData predicates to filter all the child data of a given parent


There are two entities Child and Parent. Parent and Child is one to many relationship, one Parent with many Child.

The code I referred to is as following and it can filter all the data of Child level whose Attribute text contains yes:

@State private var predicate: NSPredicate? = NSPredicate(format: "text contains[c] %@", "yes")
@ObservedObject private var db = CoreDataDB<Child>()

for child in self.db.loadDB(predicate: self.predicate):
    ....

What I want to do is to get all the Child level's data belong to current Child data's Parent.

var child: Child

// How to write this line???
@State private var predicate: NSPredicate? = NSPredicate(format: "parent = %@", "self.child.parent")

@ObservedObject private var db = CoreDataDB<Child>()

for child in self.db.loadDB(predicate: self.predicate):
    ....

I do not know how to write the predicate above to filter data that belong to the same Parent with current child in current child's View.

NSPredicate(format: "parent = %@", "self.child.parent") will get nothing when for child in self.db.loadDB(predicate: self.predicate):.

NSPredicate(format: "child.parent = %@", "self.child.parent") will get error saying keypath child.parent not found in entity <NSSQLEntity Child id=1> with userInfo of (null)

What I need to say is that text of Child Entity in the code is an Attribute I created, but parent of Child Entity is auto created by the one to many relationship with Parent Entity. I cannot see parent Attribute in xcdataModelId file but I can use it in the code.

Thanks for any help.


Solution

  • Here

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

    you substitute a string for the %@ placeholder. What you want is

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

    which searches for all entities whose parent is equal to the parent of self.child.