Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 667
Lee Probert Avatar asked Feb 17 '23 15:02

Lee Probert


2 Answers

Check the entity like this:

[NSPredicate predicateWithFormat:@"self.entity = %@", Person.entity];
like image 65
malhal Avatar answered Mar 11 '23 01:03

malhal


Swift 4.0 way of checking for entity type using the entity property of the NSManagedObject as per malhal's suggestion.

let entityDescription = NSEntityDescription.entity(forEntityName: "Account", in: managedObjectContext)!
return NSPredicate(format: "entity = %@", entityDescription)
like image 32
Stuart Pattison Avatar answered Mar 11 '23 02:03

Stuart Pattison