Search code examples
objective-ccore-datarelationshipnsfetchrequest

NSFetchRequest - get all objects by relationship


It's possible create aNSFetcherRequest or something similar for get all objects by relationship? For example I have three entities student, absence and subject. Student has attributes NSSet absence, absence has attribute student and subject. I need get all absence of one student and one subject. So I need require similar this pseudo code: select all absence where student=="concrete student" and where subject=="concrete subject". But it aren't attributes, but relationship! How can I do it? I know, that I can get all absence of student and than filter it, but I think, its very inefficient.


Solution

  • Both attributes and relationships are properties of a managed object and can be used as key path in a predicate, for example:

     Student *concreteStudent = ...;
     Subject *concreteSubject = ...;
     NSPredicate *predicate = [NSPredicate predicateWithFormat:@"student = %@ AND subject = %@",
         concreteStudent, concreteSubject];
     NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Absence"];
     fetchRequest.predicate = predicate;
    

    if "student" and "subject" are to-one relationships of the Absence entity.