CoreData - select specific entry from one to many relationship

Damn you short titles! :p

Basically I have an entity named "threads" and I have an entity named "messages". I have a one to many relationship from threads ->> messages (and a one to one inverse relationship).

What I need to do is get all the records from the threads entity and for each one I need to get the message with the latest timestamp (this is just an int in the "lastUpdated" attribute, so the highest number I guess will suffice).

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

I'm sure there must be a better way than iterating through all the records and comparing the threadIds?

Thank you.

Answers


Once you have the individual Thread objects, you just need to do a sort on the Messages objects and take the topmost Message object.

The easiest solution would be to create a method in the Thread class like this:

- (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 linking entity that would link one Message object to one Thread object and set that link object as the Message objects update. So:

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

Whenever a Message object updated, it would tell it's related Thread object to delete the existing link object and create another one pointing to it. You would probably put that code in a custom setter for the lastUpdated property.

With this method you just have to ask each thread for its lastUpdatedMessage and it appears automatically without a lot of searching and sorting.


Need Your Help

GWT Error - Unable to see output in Browser using DocLayoutPanel

java gwt java-ee

I am writing a application using DocLayout Panel. The problem is that I can see the result in the GWT designer but the same output is not appearing when I am trying to run the application. Can anyone

Unfortunately <application> has stopped

android http post

I have an app where the user submits some data in a form which is then sent to a server. I am testing it on a tablet and an Android smartphone (Galaxy S2). On the tablet, as soon as I click on "Sub...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.