1 year ago
#384107
Mrugesh Tank
A Core data Sort on Relationship's Attribute in ios Swift
I'm having 2 entities CDChatConversation
and CDMessage
. CDConversation
having to many
relationship with messages.
I want to fetch all conversation with sorting of lastMessage's datetime attribute which is kind of Date
.
Currently I'm using following predicate and FetchRequest but I think this will take more time when I'm having more data.
func getChatConversationSorted() throws -> [CDChatConversation] {
let fetchRequest: NSFetchRequest<CDMessage> = CDMessage.fetchRequest()
let timePredicate = NSPredicate(format: "dateTime = conversation.messages.@max.dateTime")
fetchRequest.predicate = timePredicate
fetchRequest.sortDescriptors = [NSSortDescriptor(key: #keyPath(CDMessage.dateTime), ascending: false)]
let fetchedMessages = try context.fetch(fetchRequest)
let fetchedConversations = fetchedMessages.compactMap({$0.conversation})
return fetchedConversations
}
How can I directly predicate on CDChatConversation
?
ios
swift
core-data
local-database
0 Answers
Your Answer