4

I'm building an open-source clone of iPhone's native Messages app called AcaniChat on GitHub.

I have a Conversation entity and a Message entity with a sentDate attribute. Each Conversation can have many Messages. How do I fetch Conversations sorted by the sentDate of it's oldest Message?

ma11hew28
  • 121,420
  • 116
  • 450
  • 651

1 Answers1

1

The best way I can think of doing this is by adding an attribute to the Conversation entity called lastMessageSentDate and, every time a Message comes in and gets added to a Conversation, setting that conversation's lastMessageSentDate to that message's sentDate. I'll also probably want to add an attribute called lastMessageText to the Conversation entity as well because I want to show the text of the last message for a conversation on the ConversationsViewController (just like the native iPhone Messages app does), and doing so will save me from having to do another Core Data fetch for the Message.

Actually, I just had an idea! Maybe I can sort Conversations by messages.@max.sortedDate, according to Xcode Documentation: Key-Value Coding Programming Guide: Collection Operators.

Chris Frederick
  • 5,482
  • 3
  • 36
  • 44
ma11hew28
  • 121,420
  • 116
  • 450
  • 651
  • Your first idea might be more efficient since it eliminates the need to compute the maximum date for each Conversation.messages collection every time you fetch Conversations! – octy Jun 13 '11 at 16:11
  • or just have a `lastMessage` in a `Conversation` instead of `lastMessageSentDate` and `lastMessageText` :) – Filipe Pina Apr 16 '12 at 11:02
  • 2
    @MattDiPasquale I tried your idea. It didn’t work. See related question: http://stackoverflow.com/questions/12748852/how-to-sort-core-data-results-based-on-an-attribute-of-related-object-collection – Jaanus Oct 05 '12 at 15:32