Search code examples
iosnsfetchrequest

how to use subquery or how to fetch data


I use core-data and hava 2 embadded relationship to-many. Also i have a calendare, and I should dowload all medicines from all diseases at selected DATE. How I can do it with subquery or using subquery?

Disease ->>Medicine->>Date

screenshot is here http://savepic.ru/4608231.png

Couild I search all medicine without binding with disease?

NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:[NSEntityDescription entityForName:@"MyMedicine" inManagedObjectContext:objectContext]];
[request setSortDescriptors:[NSArray initWithObject:[[NSSortDescriptor alloc] initWithKey:@"firstName" ascending:YES]];
[request setPredicate:[NSPredicate predicateWithFormat:@"(data == %@)", currentData]];

Solution

  • Assuming you initialize your NSFetchRequest like this:

    NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
    [request setEntity:[NSEntityDescription entityForName:@"MyMedicine" inManagedObjectContext:objectContext]];
    [request setSortDescriptors:[NSArray initWithObject:[[NSSortDescriptor alloc] initWithKey:@"firstName" ascending:YES]];
    

    You may setup your predicate like this:

    // Dates
    [request setPredicate:[NSPredicate predicateWithFormat:@"date == %@", datesEntity]];
    

    or

    // NSDate
    [request setPredicate:[NSPredicate predicateWithFormat:@"date.date == %@", date]];
    

    As a default all the relations will be fetched as faults, if you need them to be fetched during this fetch you could configure relationship key paths to be fetched in this fetch like this:

    NSArray* relationKeys = [NSArray arrayWithObject:@"disease"];
    [request setRelationshipKeyPathsForPrefetching:relationKeys];
    

    Using this approach all the related Disease entities will be fetched along with all matching Dates entities.