2013-10-08 13 views
0

我在制作一个聊天应用程序。使用以下格式的核心数据存储消息:核心数据聊天应用程序获取按日期排序的一批消息

@property (nonatomic, retain) NSDate * datetime; 
@property (nonatomic, retain) NSString * text; 
@property (nonatomic, retain) NSString * type; 
@property (nonatomic, retain) NSNumber * sent; 
@property (nonatomic, retain) NSNumber * read; 
@property (nonatomic, retain) DBRoom *room; 
@property (nonatomic, retain) DBUser *sender; 

现在我需要检索聊天室的消息。我原来的实现很简单:

self.messages = [Helper mutableArrayWithSet:self.currentRoom.messages sortKey:@"datetime" ascending:NO]; 

当我使用一个辅助方法mutableArrayWithSet

+ (NSMutableArray *)mutableArrayWithSet:(NSSet *)set sortKey:(NSString *)key ascending:(BOOL)ascending { 
    NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:key ascending:ascending]; 
    NSArray *array = [set sortedArrayUsingDescriptors:[NSArray arrayWithObject:descriptor]]; 
    return array.mutableCopy; 
} 

然后,我只是保持前10名的消息,并删除其余部分。当用户向上滚动以获取历史消息时,我再次获取并保存20条消息。

问题是,如果有很多消息,它可能会影响性能。我认为问题是self.currentRoom.messages。这很方便,但效率不高。

有没有办法按批次提取邮件,比如“按日期时间排序选择一批邮件(从20日到30日)”,或者“选择第3批批次为10的邮件,按日期时间排序“

编辑:

我只是通过文档阅读,发现这个:

”。您可以使用此功能来限制工作集中在应用程序中的数据与fetchLimit组合,您可以创建任意结果集的子范围 “

+0

使用['NSFetchedResultsController'](https://developer.apple.com/library/ios/documentation/CoreData/Reference/NSFetchedResultsController_Class/Reference/Reference.html)来获取消息并将其显示在'UITableViewCell'中 – rckoenes

回答

0

您可以使用NSFetchRequest- (void)setFetchBatchSize:(NSUInteger)bsize做到这一点。我不确定它是否适用于关系,因此您可能必须更改NSFetchRequest才能直接使用Message实体进行提取,而不是使用self.currentRoom.messages

+0

你的意思是取回前30名而不是取20号到30号? – OMGPOP

+0

我不确定你在问什么。 [fetchBatchSize](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/CoreDataFramework/Classes/NSFetchRequest_Class/NSFetchRequest.html#//apple_ref/occ/instm/NSFetchRequest/fetchBatchSize) - 这是一个完整的解释如何批量获取作品。 –

+0

是不是批量大小仅仅是系统加速逐批加速的提示? – OMGPOP