Search code examples
core-datansfetchedresultscontroller

FetchedResultsController sectionKeyPath on different entity


Is it possible to define a sectionKeyPath that is on a different entity?

I have a set of users which are the entities the fetchedResultsController is displaying. I would like to sort them into 2 sections, based on whether they have unread messages or not.

So I need to get the message using user.lastMessageId and then use message.viewed as the sectionKeyPath.


Solution

  • In principle you can use an attribute of a different entity as the sectionNameKeyPath for an FRC, but there must be a to-one relationship from the entity underlying the FRC to the entity with the attribute in question.

    You mention a lastMessageID attribute, which implies you are storing a unique ID to the last message. Replace this instead with a to-one relationship lastMessage to the Message entity, and populate this with the relevant Message object rather than its unique ID. You can then use lastMessage.viewed as your sectionNameKeyPath. Note that you will also need to add a sort descriptor to sort the FRC entities by the same key.