Fetch Grouped Data from Core Data
I have data in a table of messages. These messages are some sort of chat messages. Now I want to fetch the data in form of conversations like this...
Let's suppose we have a,b,c,d,e,f and m users. m is for myself. Now there are messages having senders from a,b,c,d,e,f and m and same is for receiver. All of the messages has m as sender or receiver and one object from other users. Now I want the data to be grouped as..
All messages having messages sent to a or received from a
All messages having messages sent to b or received from b
All messages having messages sent to c or received from c
and so on....
Can any one suggest how I may do that. I've looked into some questions but couldn't find the answer. Any one there to help would be appreciable.
Using a Fetched Results Controller, you have to consider that some messages will be included more than once.
1) Fetch User entity, sort by name
2) Number of sections: fetchedObjects.count
3) Number of rows in section:
NSSet *allMessages = [user.receivedMessages setByAddingObjectsFromSet:user.sentMessages]; return allMessages.count;
4) Populate the cell:
NSSet *allMessages = [user.receivedMessages setByAddingObjectsFromSet:user.sentMessages]; NSArray *sorted = [allMessages sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"message.topic" ascending:YES]]]; Message *m = sorted[indexPath.row];
This can be simplified by adding a transient property to Userthat returns the sorted allMessages. Please not that doing this directly in the datasource methods is not very efficient, I just put it here to illustrate the point.
You can use NSFetchedresultscontroller if is in viewController result. This Object contains a section and row in the result data