I am using CoreData for an iPhone project and I am stuck trying to build a predicate.
My core data entity is
Folder
parent - Point to the folder class parent, can be null and is one to one.
secure - An enum that holds the security type.
The problem I have is that I am trying to make it so I don’t show any folder that are in a secure folder.
Right now my predicate looks something like this.
NSPredicate *pred = [NSPredicate predicateWithFormat:@"secure = $@ AND (parent = %@ OR parent.secure = %@)",[NSNumber numberWithInteger:kNoSecurity], [NSNull null], [NSNumber numberWithInteger:kNoSecurity]];
This works find when I only have a chain like folder1 -> folder2 and folder1 is secure. But if I have folder1 -> folder2 -> folder3 (folder2 and folder3 are not secure). Folder3 gets returned because I only check one level up. Is there a way to get the predicate to do the check for a entire chain?
Thanks.
You can’t recursively walk relationships in predicates because keypaths only describe the relationship between the abstract entities and not the concrete, living managed objects that actually contain the data. An entity graph can be very simple yet generate a vastly complex graph of live objects when populated at runtime. You can’t logically capture the complexity of that live graph with a simple keypath.
In this case, you have a
Folderentity which has a relationship to itself calledparentand an attribute ofsecure. Therefore, a keypath can only describe at most those two properties with pathparent.secure. You can’t create a keypath ofparent.parent.securebecause no such relationship actually exists in the entity graph. Such a path only exist sometimes in the live object graph. It would be logically impossible to hard code a path that might or might not exist depending on the particulars of the data at any given time.This type of situation is where the ability to create customized NSManagedObject subclasses really comes in handy. Your
Folderentites don’t have to be just dumb data, you can add behaviors to them so that each object can access its own state and return different data as needed.In this case, I would recommend adding a transient boolean property named something like
hasSecureAncestor. Then create a custom getter method like:Then just create a predicate to test for “hasSecureAncestor==YES”. The custom accessor will walk an arbitrarily deep recursive relationship looking for a secure ancestor.