有没有人知道如何使用NSSortDescriptors进行嵌套排序(不确定它是否是最佳术语)?
我正在使用NSSortDescriptors来获取NSManagedObjects。
我有一个名为Conversation的NSManagedObject,它与Messages有一对多的关系。每个Conversation都有一组NSSet消息。
每条消息都有一个timeReceived Date属性。我正试图通过各自最新消息的timeReceiveds
对我的对话进行排序要重申:我正在尝试在每次对话中找到最后一次收到的消息,然后按对应的最新消息对对话进行排序。消息和对话是NSManagedObjects。
这些描述符的键字符串性质使我很难弄明白。
我在SO上看到了一些建议: NSSortDescriptor * sortByDate = [NSSortDescriptor sortDescriptorWithKey:@“messages。@min.timeReceived”ascending:NO];
但我刚刚崩溃了:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Keypath containing KVC aggregate where there shouldn't be one; failed to handle messages.@max.timeReceived'
你们之前有没有做过这样的事情?
- (NSFetchedResultsController *) fetchSortedConversations
{
NSSortDescriptor *sortByDate = [NSSortDescriptor sortDescriptorWithKey:@"latestMessage.timeReceived" ascending:NO];
// I implemented a workaround where I set a latestMessage for each Conversation somewhere else, but I'd like to be able to sort the Conversations without having to manually manage the latest message.
NSArray * sortDescriptors = @[sortByDate];
NSFetchedResultsController * conversations = [self.coreDataManager fetchEntitiesWithName: NSStringFromClass([Conversation class]) sortDescriptors:sortDescriptors sectionNameKeyPath:nil predicate:nil];
return conversations;
}
答案 0 :(得分:3)
我认为你所面临的问题无法用目前制定的NSFetchedResultsController
来解决,因为它无法在SQL中得到很好的解决。所以NSFetchRequest
可能只是拒绝这样做,并且气泡向上。
最简单的解决方案是在您为- willSave
获取的托管对象子类上实现Conversation
,并在该@max.timeReceived
中实现Conversation
并将其直接存储在{{1}中的属性中}}。然后告诉你的提取结果控制器对它进行排序。