CoreData - Choose a specific record from one to many relationships

Damn you !: P

Basically, I have an object called "threads", and I have an object called "messages". I have a relationship from one to many of the threads →> messages (and from one to one inverse relationship).

I need to make all entries from the essence of the streams and for each of them I need to get a message with the last timestamp (this is just an int in the lastUpdated attribute, so the largest number that I assume will be enough).

I'm not sure what other information you might want, here is a screenshot of my entities:

alt text

I'm sure there should be a better way than repeating all entries and comparing threadIds?

Thank.

+3
source share
3 answers

Once you have separate Thread objects, you just need to sort by the Message objects and take the topmost Message object.

The simplest solution is to create a method in the Thread class as follows:

- (Messages *) lastUpdatedMessage{
    NSSortDescriptor *sort=[NSSortDescriptor sortDescriptorWithKey:@"lastUpdated" ascending:NO];
    NSArray *sortedMessages=[self.messagesInThread sortedArrayUsingDescriptors:[NSArray arrayWithObject:sort]];
    return [sortedMessages objectAtIndex:0];
}

Then all you have to do is ask each Thread object for its lastUpdatedMessage.

A more complex but more efficient solution would be to create an intermediate binding object that binds one Message object to one Thread object and sets this link object as an update to the message objects. So:

MessageThreadLink{
    message<--(required)-->Message.lastUpdateLink
    thread<--(required)-->Thread.lastUpdatedMessage
}

, , Thread , . , lastUpdated.

lastUpdatedMessage, .

+3

NSPredicate, , , 'd ? (, , )

0

, - int, NSDate? , int - , ?

, BOOL, lastUpdated == YES, , , , . - " ", , .

[] , , , Thread , .

2

NSDate , , , /.

Then for each saved stream, pull out the corresponding messages, sort them by NSDate and select the first object in the array if ASCENDING == NO or the last object if ASCENDING == YES.

0
source

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


All Articles