2012-07-19 65 views
0

我有我的聊天應用程序中的下列對象(一個一對多的關係)NSPredicate在集合中最新的項目

@interface ChatEntry : NSManagedObject 
@property (nonatomic, retain) NSString * text; 
@property (nonatomic, retain) NSDate * timestamp; 
@property (nonatomic, retain) ChatContext *context; 
@end 

@interface ChatContext : NSManagedObject 
@property (nonatomic, retain) NSString * name; 
@property (nonatomic, retain) NSString * userId; 
@property (nonatomic, retain) NSSet *entries; 
@end 

每個會話(ChatContext)組的所有消息由該用戶發送(唯一標識由userId字段)。

我試圖顯示會話列表,顯示每個會話的最後一條消息(類似於iMessage)。

我用下面的代碼:

NSFetchRequest* request=[[NSFetchRequest alloc] initWithEntityName:@"ChatEntry"]; 
request.predicate=[NSPredicate predicateWithFormat:@"[email protected]"]; 
request.sortDescriptors=[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"timestamp" ascending:NO]]; 
m_chat=[[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:m_context sectionNameKeyPath:nil cacheName:@"chat"]; 
m_chat.delegate=self; 

,直到我收到一個新的消息(與NSFetchedResultsChangeInsert)這工作得很好

- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath 
{ 
... 
} 

在這一點上,我得到我的表中的另一個條目視圖。 fetch控制器保留先前的條目(儘管它的時間戳不再是最新的條目)。我不知道如何解決這個問題,並迫使控制器總是評估謂詞。

另外,我試圖改變我的查詢來獲取ChatContext實例,但是我不確定如何實際讀取該上下文中的最新條目。

+0

你解決了嗎? – 2013-07-31 22:59:21

+0

查看我的答案 – 2013-08-02 01:44:47

回答

0

好的,我已經設法解決這個問題。我所做的是在上下文中添加一個「lastMessage」對象,並在每條新消息中不斷更新。然後,我查詢上下文列表,按逆向排序lastMessage.timestamp。新消息在其上下文中更新lastMessage屬性 - 這會觸發事件並自動更新UI。