FMDB, GCD, and NSOperationQueue

I have a lot of data that I need to insert into two tables for my sqlite database. I want to put this work in the background. My stream basically looks like this: (pseudocode)

while (files in database are not parsed) {

if (fileType == type1) {
   parseType1;
   showProgress;
}
else {
   parseType2;
   showProgress;
}
}

I got the latest version of FMDB, and I thought I could write my data as follows:

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];
}

Both parseType methods are as follows. When I run it myself, I get the error message that FMDatabase uses. Is it because I need to queue both in the same method against separate methods? I also tried something like this:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0) ^{
   parseType1;
});
dispatch_async(dispatch_get_main_queue, ^{
   update UI;
});

But I get the same problem as db currently. Am I using FMDatabaseQueue correctly? Or do I need to do something different? If I use NSOperationQueue here instead of GCD, is that better? Thank!

0
source share

All Articles