Search code examples
ioscore-dataone-to-manynsfetchedresultscontrollernsfetchrequest

NSFetchedResultsController on a one-to-many relationship


I am implementing an NSIncrementalStore and I need to perform a paginated fetch and maintain the order of the elements within the request, then display the results in a table and maintain an NSFetchedResultsController associated with the query. I will try to explain my self better with an example

I have two entities, Entity1 and Entity2. Entity1 has a one-to-many relationship with Entity2 and since the fetch implies too many objects I want to perform a paginated request. I need to maintain the order of the objects arriving from the server so the objects are stored in an NSOrderSet. There is no inverse relation between Entity2 and Entity1.

The problem I am having is that I don't know how to instantiate the NSFetchRequest in this case.

I've read about pre-fetched relationships using setRelationshipKeyPathsForPrefetching but the NSFetchRequest its instantiated with Entity1 as entity ([fetchRequest setEntity:[Entity1 class]]) in all examples I read. I need a set of Entity2 objects.

Another idea was to use a fetched property but since I can't (and I don't want to) perform a sort on the request, I discarded it.

I hope I was clear and thanks Marcus Zarra in advance for encouraging me to ask this question.

Thanks a lot.


Solution

  • First, you need an inverse relationship. Core Data really should require them instead of just a warning. With an inverse this question becomes simple. Without an inverse it is all but impossible.

    Assuming you add the inverse (as you should :) then you set up your NSFetchRequest against Entity2 with a predicate of "entity1 == %@" and you will get your results back. From there you can adjust the NSFetchRequest to handle the pagination.