我有一个基于导航控制器的聊天应用程序。
在显示对话的视图中,我在viewDidLoad
方法中从SQLite加载所有以前的历史记录。
当谈话增加时,打开视图需要几秒钟,因此感觉“迟钝”。
以下是我用来从数据库加载历史记录的代码。
有哪些想法可以改进以使用户界面感觉更具响应性?
NSString *sql = [NSString stringWithFormat:@"SELECT * FROM chatHistory WHERE channelID = '%@' ORDER BY time ASC", box.activeChannel];
sqlite3_stmt *statement;
if(sqlite3_prepare_v2([box db], [sql UTF8String], -1, &statement, nil) == SQLITE_OK) {
while(sqlite3_step(statement) == SQLITE_ROW) {
char *field1 = (char *) sqlite3_column_text(statement, 0);
NSString *channelID = [[NSString alloc] initWithUTF8String:field1];
char *field2 = (char *) sqlite3_column_text(statement, 1);
NSString *sender = [[NSString alloc] initWithUTF8String:field2];
char *field3 = (char *) sqlite3_column_text(statement, 2);
NSString *message = [[NSString alloc] initWithUTF8String:field3];
char *field4 = (char *) sqlite3_column_text(statement, 3);
NSString *recipient = [[NSString alloc] initWithUTF8String:field4];
char *field5 = (char *) sqlite3_column_text(statement, 4);
NSString *time = [[NSString alloc] initWithUTF8String:field5];
NSString *str = [[NSString alloc] initWithFormat:@"%@", message];
NSString *str1 = [[NSString alloc] initWithFormat:@"%@", channelID];
NSString *str2 = [[NSString alloc] initWithFormat:@"%@", sender];
NSString *str3 = [[NSString alloc] initWithFormat:@"%@", time];
NSString *trimmedStr2 = [str2 stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceCharacterSet]];
NSString *trimmedAgentName = [box.agentName stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceCharacterSet]];
NSString *trimmedTime = [str3 stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceCharacterSet]];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-MM-dd HH:mm:ss ZZZ"];
NSDate *myDate = [df dateFromString:trimmedTime];
if ([trimmedStr2 isEqualToString:trimmedAgentName]) {
[self.messages addObject:[[JSMessage alloc] initWithText:str sender:trimmedAgentName date:myDate]];
[self finishSend];
[self scrollToBottomAnimated:YES];
} else {
[self.messages addObject:[[JSMessage alloc] initWithText:str sender:kSubtitleVisitor date:myDate]];
[self finishSend];
[self scrollToBottomAnimated:YES];
}
}
}
修改
我还尝试将代码置于dispatch_queue
内,这使得切换到视图的速度要快得多,但添加时消息仍然落后。
答案 0 :(得分:0)
您可以在代码中优化某些地方:
str
str1
str2
str3
,只需使用message
channelID
sender
{{1} }。time
创建是广泛的,你应该在while循环之外创建一个实例。NSDateFormatter
,查询将花费很长时间来执行和阻止UI,您可能希望在后台执行SQL查询。有关详情,请参阅Apple的Concurrency Programming Guide。