我需要在sqlite数据库的两个表中插入大量数据。我想把这项工作放在后台。我的流程基本上是这样的:(伪代码)
while (files in database are not parsed) {
if (fileType == type1) {
parseType1;
showProgress;
}
else {
parseType2;
showProgress;
}
}
我收到了FMDB的最新版本,我想我可以将这些数据排入队列:
FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:[self databasePath]];
BOOL oldshouldcachestatements = _db.shouldCacheStatements;
[_db setShouldCacheStatements:YES];
[_db beginTransaction];
NSString *insertQuery = [[NSString alloc] initWithFormat:@"INSERT INTO %@ values(null, ?, ?, ?, ?);", tableName];
[tableName release];
__block BOOL success;
// Parse each line by tabs
for (NSString *line in lines) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSArray *fields = [line componentsSeparatedByString:@"\t"];
// Need to check since some of the .txt files have an empty newline at the EOF.
if ([fields count] == NUM_FIELDS) {
NSNumber *start = [NSNumber numberWithInteger:[[fields objectAtIndex:1] integerValue]];
NSNumber *end = [NSNumber numberWithInteger:[[fields objectAtIndex:2] integerValue]];
NSNumber *length = [NSNumber numberWithInteger:([end integerValue] - [start integerValue])];
NSArray *argArray = [[NSArray alloc] initWithObjects:ID, start, end, length, nil];
[queue inDatabase:^(FMDatabase *db) {
success = [_db executeUpdate:insertQuery withArgumentsInArray:argArray];
}];
[argArray release];
}
[pool drain];
}
我的parseType方法都是这样的。当我自己运行它时,我得到FMDatabase当前正在使用的错误。是因为我需要在同一方法中将两者放入队列中而不是单独的方法吗?我也试过这样的事情:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0) ^{
parseType1;
});
dispatch_async(dispatch_get_main_queue, ^{
update UI;
});
但是我遇到了db当前正在使用的相同问题。我正确使用FMDatabaseQueue吗?或者我需要做一些不同的事情吗?如果我在这里使用NSOperationQueue而不是GCD那更好吗?谢谢!