Search code examples
core-datanspredicatensfetchrequest

Evaluate CoreData entity type in predicate


I have a block predicate that I carefully crafted only to discover you can't use them in Core Data.

NSPredicate *rootContactPredicate = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {

        BOOL isPersonAndRoot = ([[[evaluatedObject entity] name] isEqualToString:@"Person"] && [[(Person*)evaluatedObject accounts] count] == 0);
        BOOL isAccountAndRoot = ([[[evaluatedObject entity] name] isEqualToString:@"Account"] && [(Account*)evaluatedObject root] == nil);

        return isPersonAndRoot || isAccountAndRoot;
    }];

So I need to convert this into a standard String format predicate, but I am unclear on how to check the entity type for the evaluated object. The Person and Account entities are subclasses of a Contact entity which is the type being evaluated in the fetch request. I'm hoping it will see the sub-types.


Solution

  • It seems that now you can now simply compare the entity in a predicate, supplying the managed objects entity as the value:

    "entity = %@"
    

    Previously:

    You can't. The reason is that the predicate will need to be converted so that it can be run on the underlying data store (presumably SQLite). The SQLite database doesn't have any data on the type of the element, it only knows about the keys and values of the objects.

    Depending on what you're trying to do, you'll either need to run a single fetch request against the keys known in the super entity. Or you'd need to have 2 fetch requests, separately executed and then combine the 2 result sets.