Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective C - one-many relationships data retrival from core data

enter image description here

I have a core data model (has made a simplifie to make it easier to explain what I want to do).

An author can published many books and a book can have many chapters. In the example I want to retreive all the Autors that has a chapter in a book where readDate is null.

- (NSArray *)incompleteChaptersInManagedObjectContext:(NSManagedObjectContext *)context
{
    NSFetchRequest* fetch = [NSFetchRequest fetchRequestWithEntityName:NSStringFromClass([Author class])];
    NSPredicate* uidCondition = [NSPredicate predicateWithFormat:@"books.chapters.readDate!=nil"];
    [fetch setPredicate:uidCondition];

    NSArray* resultArray = [context executeFetchRequest:fetch error:&error];

..
..

This does not work and I am struggling finding out how this can be done. At the moment I am declare an author mutablearray. - get all authors - loop through all their books - loop through all the chapters - if readDate is null add it to the author array

This works but I want to solve this without the nested loops.

like image 204
reachify Avatar asked Jul 09 '13 12:07

reachify


People also ask

What are relationships in Core Data?

Inverse relationships enable Core Data to propagate change in both directions when an instance of either the source or destination type changes. Every relationship must have an inverse. When creating relationships in the Graph editor, you add inverse relationships between entities in a single step.

What are fetched properties in Core Data?

Fetched Properties in Core Data are properties that return an array value from a predicate. A fetched property predicate is a Core Data query that evaluates to an array of results.

How do I use Core Data?

Use Core Data to save your application's permanent data for offline use, to cache temporary data, and to add undo functionality to your app on a single device. To sync data across multiple devices in a single iCloud account, Core Data automatically mirrors your schema to a CloudKit container.

How do you start your NSFetchRequest?

You initialize an instance of NSFetchRequest as generic type: NSFetchRequest<Venue> . At a minimum, you must specify a NSEntityDescription for the fetch request. In this case, the entity is Venue . You initialize an instance of NSEntityDescription and use it to set the fetch request's entity property.


1 Answers

For nested to-many relationships a SUBQUERY is necessary (as @geo already correctly said). But one SUBQUERY should be sufficient:

[NSPredicate predicateWithFormat:@"SUBQUERY(books, $b, ANY $b.chapters.readData == NULL).@count > 0"]

(I assume that "books" and "chapters" are really to-many relationships, even if your diagram show them as to-one relationship.)

like image 170
Martin R Avatar answered Oct 14 '22 10:10

Martin R