有没有办法加速SQLite获取?

时间:2011-08-08 02:02:31

标签: iphone objective-c database xcode sqlite

有没有办法加速SQLite Fetch? 我从我的SQLite数据库中获取数据到一个加载我的tableView的数组。

填充阵列大约需要10-20秒。有没有更快的方法来做这个或什么?也许只能一次加载每个单元格,所以至少用户看到一些单元格,而其余单元格正在加载?

以下是我的ViewController中的代码: 代码:

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [NSThread detachNewThreadSelector:@selector(myThread:) toTarget:self withObject:nil]; 
}
-(void) myThread:(id) obj {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSMutableArray *array = [[Database sharedDatabase] getICD9DiseaseCodes];
    [self performSelectorOnMainThread:@selector(dataDoneLoading:) withObject:array waitUntilDone:NO];
    [pool release];    
}

-(void) dataDoneLoading:(id) obj {
    NSMutableArray *array = (NSMutableArray *) obj;
    self.codeAray = array;
    [self.myTableView reloadData];
}

以下是实际获取的代码: 代码:

-(NSMutableArray *) getICD9ProcedureCodes
{
    sqlite3 *database = CodesDatabase();
    NSMutableArray *icd9ProcedureCodes = [[[NSMutableArray alloc] init] autorelease];

    NSString *nsquery = [[NSString alloc] initWithFormat:@"SELECT code, title, description FROM icd9_procedure_codes"];
    const char *query = [nsquery UTF8String];
    [nsquery release];

    sqlite3_stmt *statement;
    int prepareCode = (sqlite3_prepare_v2( database, query, -1, &statement, NULL));
    if(prepareCode == SQLITE_OK) {
        while (sqlite3_step(statement) == SQLITE_ROW)
        {
            ICD9DiseaseCodes *code = [[ICD9DiseaseCodes alloc] init];
            code.code = [NSString stringWithCString:(char *)sqlite3_column_text(statement, 0) encoding:NSUTF8StringEncoding];
            code.name = [NSString stringWithCString:(char *)sqlite3_column_text(statement, 1) encoding:NSUTF8StringEncoding];
            code.description = [NSString stringWithCString:(char *)sqlite3_column_text(statement, 2) encoding:NSUTF8StringEncoding];
            [icd9ProcedureCodes addObject:code];
            [code release];
        }
        sqlite3_finalize(statement);
    }
    return icd9ProcedureCodes;
}

1 个答案:

答案 0 :(得分:2)

您绝对应该只加载您需要的那些行。使用SQL LIMIT和OFFSET选项仅加载您需要的内容。

我不知道一次只读一行是否足够快,但值得一试。类似的东西:

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
   NSString *queryString = [NSString stringWithFormat: @"SELECT code, title, description FROM icd9_procedure_codes ORDER BY ROWID LIMIT 1 OFFSET %d", indexPath.row];

   // perform your database SELECT operation here

   // set up your UITableViewCell with whatever results you want to display
   cell.textLabel.text = code.name;
}

您还应该确保在cellForRowAtIndexPath中重用UITableViewCell。