Core Data: Sort by Relationship's Attribute

为君一笑 提交于 2019-12-24 17:53:38

问题


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?


回答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.



来源:https://stackoverflow.com/questions/5768123/core-data-sort-by-relationships-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!