The main data problem - select the group by / s max.

Let's say I have two entities:

Entities

Each message belongs to one MessageThread. How to get all message flows and the corresponding last message in this thread? Typically, in SQL, I would do it like:

select __ from the message group by stream having timeStamp = max (timeStamp)

First, I don’t think Core Data allows @max in its predicates. Any ideas?

+2
source share
2 answers

It may be a little old, but lately I have had a similar problem. Here is my solution to the problem:

NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Message"]; request.predicate = [NSPredicate predicateWithFormat:@"timeStamp = thread.messages.@max.timeStamp "]; request.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"timeStamp" ascending:NO]]; 

Hope this helps ...

+2
source

I could never work @max , and I'm still looking for a better implementation.

What I do as porkaround is to set the sort handle to sort by date, and then use objectAtIndex:0 from fetchedResults.

0
source

Source: https://habr.com/ru/post/927052/


All Articles