Search code examples
iosiphonesortingcore-datansfetchrequest

Core Data: sorting by date attribute in a to-many relationship


I have the following model:

  Entities:  Entity <----------->> SubEntity
++++++++++++++++++++++++++++++++++++++++++++++++
Attributes:  >name                 >uuid
             >identifier           >date

Problem #1: I have a fetch request for Entities. I want to sort the fetch by the latest date of all the SubEntities in each Entity. How would I do that?

Problem #2: Furthermore, the fetch request has resultType = NSDictionaryResultType and in the returned dictionary, I would like to fetch the properties name and latestDate (the latest date of all the SubEntities in that Entity). Is that possible?


Solution

  • My suggestion for you would be to change your model:

    Add a latestDate property to Entity When updating a SubEntity.entity property, check if the SubEntity date is the latest for this Entity object and update accordingly.

    This will allow you to accomplish what you need with a simple query, and you will then be able to use a fetched results controller to track your data changes.

    If you cannot restructure your model, look at @Michal K's answer, but prefetch ALL your Entity and SubEntity object (2 requests), and only then use his algorithm.