有谁知道如何使用NSSortDescriptors进行嵌套排序(不确定是否是最好的术语)?

我正在使用NSSortDescriptors来获取NSManagedObjects。

我有一个称为对话的NSManagedObject,它与消息具有一对多的关系。每个会话都有一个NSSet消息。

每个消息都有一个timeReceived Date属性。我正在尝试按各自最新消息的时间对会话进行排序

重申一下:我正在尝试查找每个对话中最后一次收到的消息,然后按照对话各自的最新消息对对话进行排序。消息和对话是NSManagedObjects。

这些描述符的键字符串性质使我很难弄清楚。

我在SO上看到一些建议,例如:
NSSortDescriptor * sortByDate = [NSSortDescriptor sortDescriptorWithKey:@“ messages。@ min.timeReceived”升序:否];

但是我只是崩溃了:

 *** 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;
}

最佳答案

我认为您当前面临的问题无法通过当前制定的NSFetchedResultsController解决,因为它实际上无法在SQL中完美解决。因此,NSFetchRequest可能只是拒绝这样做,并且会冒起。

最简单的解决方案是在您为- willSave获得的托管对象子类上实现Conversation,然后在其中找到@max.timeReceived并将其直接存储到Conversation中的属性中。然后告诉您的提取结果控制器对此进行排序。

07-28 02:31
查看更多