我有一个包含 5000 行的 SQLite 数据库,已加载到 TableView 中。
加载表格大约需要 5-10 秒(这在 iPhone 上非常长)。有没有办法可以小批量加载单元格或其他方法来加快速度?另外,当我返回层次结构然后重新访问此 View 时,它必须重新重新加载。我可以将其缓存出来吗?
- (void)viewDidLoad
{
[super viewDidLoad];
[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];
[self dismissHUD];
NSLog(@"done");
}
在我的数据库类中:
-(NSMutableArray *) getICD9DiseaseCodes
{
sqlite3 *database = CodesDatabase();
NSMutableArray *icd9DiseaseCodes = [[[NSMutableArray alloc] init] autorelease];
NSString *nsquery = [[NSString alloc] initWithFormat:@"SELECT code, title, description FROM icd9_disease_codes ORDER BY code"];
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];
[icd9DiseaseCodes addObject:code];
// NSLog(@"Code: %@ Short Description: %@ Long Description: %@", hcpcsCode.code, hcpcsCode.name, hcpcsCode.description);
[code release];
}
sqlite3_finalize(statement);
}
return icd9DiseaseCodes;
}
最佳答案
我的第一个问题是为什么直接使用 SQLite,而不是 Core Data? Core Data 将为您免费从数据存储中快速进行部分提取,无需您额外编写代码。
如果您想直接使用 SQLite 手动执行相同的操作,那么您将需要编写一些繁重的代码。您需要在 SQL 查询中使用 LIMIT
和 OFFSET
来获取部分数据,并扩展您的 API 以一次仅获取较小的子集。
关于iphone - 需要优化 SQLite 加载到 TableView 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6979805/