在我的应用程序中,我使用以下两种方法:
- (NSString *)Method1:(NSString *)identificativo :(int)idUtente {
fileMgr = [NSFileManager defaultManager];
sqlite3_stmt *stmt=nil;
sqlite3 *dbase;
NSString *ora;
NSString *database = [self.GetDocumentDirectory stringByAppendingPathComponent:@"db.sqlite"];
sqlite3_open([database UTF8String], &dbase);
NSString *query = [NSString stringWithFormat:@"select MAX(orario) from orari where flag=0 and nome="%@" and idutente=%d group by orario", identificativo, idUtente];
const char *sql = [query UTF8String];
sqlite3_prepare_v2(dbase, sql, -1, &stmt, NULL);
while(sqlite3_step(stmt) == SQLITE_ROW) {
NSString *orario = [NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt, 0)];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *dataV = [formatter dateFromString:orario];
ora = [formatter stringFromDate: dataV];
}
sqlite3_finalize(stmt);
sqlite3_close(dbase);
return ora;
}
第二个:
- (int)Method2:(NSString *)nomeM :(int)idUtente {
__block int conteggio = 0;
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^(void) {
fileMgr = [NSFileManager defaultManager];
sqlite3_stmt *stmt=nil;
sqlite3 *dbase;
NSString *database = [self.GetDocumentDirectory stringByAppendingPathComponent:@"db.sqlite"];
sqlite3_open([database UTF8String], &dbase);
NSString *query = [NSString stringWithFormat:@"select nome, count(*) from orari where datetime(orario)>datetime('now','localtime') and flag=0 and nome="%@" and idutente=%d group by nome", nomeM, idUtente];
const char *sql = [query UTF8String];
sqlite3_prepare_v2(dbase, sql, -1, &stmt, NULL);
while(sqlite3_step(stmt) == SQLITE_ROW) {
conteggio = [[NSNumber numberWithInt:(int)sqlite3_column_int(stmt, 1)] intValue];
}
sqlite3_finalize(stmt);
sqlite3_close(dbase);
});
return conteggio;
}
这两种方法在执行时都会将模拟器 CPU 速度发送到 100% 并阻止 UI。在第二个线程中,我尝试使用另一个线程,但它是相同的。他们正在读取的表包含大约 7000 条记录,因此它可能取决于查询的优化不佳,或者可能是其他原因。我一点头绪都没有。
编辑:这是表架构:
dataid -> integer -> Primary key
orario -> datetime
nome -> varchar (150)
flag -> integer
pos -> varchar (150)
idutente -> integer
我应该在哪里使用索引,使用哪种索引?
另一件事:现在观察表模式,我注意到有一个错误:列"nome"应该是一个 varchar(实际上它包含一个字符串),但在我的模式中是整数类型。我不知道这是否与我的问题有关,整数列如何存储文本字符串......
这些行是一个大问题:
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
它们可能需要 0.2+ 秒。 这是一个疯狂的昂贵电话。 您实际上只需要设置一次 NSDateFormatter,并让它们都使用它。 要么在循环之外设置它,要么更好的是,将其设置为静态并保留它以进行多次调用。
同样,在此:
NSString *query = [NSString stringWithFormat:@"select nome, count(*) from orari where datetime(orario)>datetime('now','localtime') and flag=0 and nome="%@" and idutente=%d group by nome", nomeM, idUtente];
如果您能够修改数据库,此解决方案可能会帮助您加快速度。
您正在为datetime('now', 'localtime')
一遍又一遍地进行相同的计算. 在数据库中存储和比较时间的方法要快得多。