This has to be a common question and I found many related here in SO, but none with the solution for this.
I have these 2 coredata models:
@class Message;
@interface Conversation : NSManagedObject
@property (nonatomic, retain) NSString * number;
@property (nonatomic, retain) NSSet *messages;
@property (nonatomic, retain) Message *lastMessage;
And
@class Conversation;
@interface Message : NSManagedObject
@property (nonatomic, retain) NSString * account;
@property (nonatomic, retain) NSDate * date;
@property (nonatomic, retain) NSString * message;
@property (nonatomic, retain) NSNumber * sentFlag;
@property (nonatomic, retain) NSString * status;
@property (nonatomic, retain) Conversation *conversation;
In my ConversationListViewController I fetch all conversations ordered by lastMessage.date.
Then the ConversationViewController receives a Conversationand lists its messages.
Right now I’m handling lastMessage manually, so every time I add a new message, in ConversationViewController, I also update conversation.lastMessage.
Is there a better way to do it?
Because right now, there’s only one place I insert/update a new message, but if there was something like insert/update triggers that’d sound better..
I know I could fetch all Conversations and then sort them with a sortdescriptor using messages.@max.date but that doesn’t sound like a good solution for a large pool of messages/conversations.
I really don’t think that there is something more elegant or any kind of better way, then setting
newMessage.conversation.lastMessage = newMessage.Core Data posts notifications, every time it adds or changes an entity, but i don’t think,that it would be easier to observe them, then adding this line of code every time you create a new message.