Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS Core data how to use NSPredicate to find parent objects based on one to many child properties?

I have a Core Data model that goes as following:

A ServiceProvider Entity can have many Service Entities(one to many relationship). Each Service has a type attribute.

How can I use the type attribute of the Service entity to search for ServiceProviders that have services with that type?

Below is an example that I currently have that works for a single service relationship. How can I modify the predicate below to work for multiple services?

  NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSManagedObjectContext* context = [HealthDataManager sharedInstance].managedObjectContext;

    NSEntityDescription *entity = [NSEntityDescription entityForName:@"ServiceProvider" inManagedObjectContext:context];
    [fetchRequest setEntity:entity];



    [fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"self.service.type == %i",type]];

    NSArray* results = [context executeFetchRequest:fetchRequest error:nil];

    if(results.count>0)
    {
        for(ServiceProvider* provider in results)
        {
            DLog(@"found provider: %@", [provider description ]);
        }
        return [results lastObject];
    }else{
        DLog(@"Creating provider" );
    }
like image 597
Alex Stone Avatar asked Dec 07 '25 23:12

Alex Stone


2 Answers

To find objects that have any related service with the given type, use the predicate

[NSPredicate predicateWithFormat:@"ANY services.type == %i",type];

(assuming that "services" is the name of the to-namy relationship).

like image 158
Martin R Avatar answered Dec 10 '25 11:12

Martin R


You need to use subqueries for that: NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(SUBQUERY(service, $service, $service.type == %i).@count) > 0"];.

For more informations about how subqueries and other predicate work you should checkout the Predicate Programming Guide.

like image 36
Gianluca Tranchedone Avatar answered Dec 10 '25 13:12

Gianluca Tranchedone



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!