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 日)”,或“选择按日期时间排序的批量大小为 10 的第三批消息”

编辑:

我刚刚阅读了文档并发现了这一点:

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

4

1 回答 1

0

您可以使用NSFetchRequest - (void)setFetchBatchSize:(NSUInteger)bsize. 我不确定它是否适用于关系,因此您可能必须将您的更改NSFetchRequest为直接使用实体获取Message,而不是使用self.currentRoom.messages.

于 2013-10-08T10:23:57.317 回答