Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keeping FMDB thread safe

Tags:

iphone

fmdb

I see in FMDB 2.0, the author added FMDatabaseQueue for threads. The example is:

// First, make your queue.

FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:aPath];
Then use it like so:

[queue inDatabase:^(FMDatabase *db) {
    [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:1]];
    [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:2]];
    [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:3]];

    FMResultSet *rs = [db executeQuery:@"select * from foo"];
    while ([rs next]) {
        …
    }
}];
// An easy way to wrap things up in a transaction can be done like this:

[queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
    [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:1]];
    [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:2]];
    [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:3]];

    if (whoopsSomethingWrongHappened) {
        *rollback = YES;
        return;
    }
    // etc…
    [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:4]];
}];

Two questions, what is the databaseQueueWithPath parameter supposed to be? Is that the path of where my database lies?

Second question, I can see how this would work if you have multiple updates and you don't want them trampling on top of each other. But what about if you are inserting data into the database, but also want to access other data in the database so the user can still play with your app while their data is being inserting. Is that possible? Thanks!

like image 485
Crystal Avatar asked Nov 03 '22 19:11

Crystal


1 Answers

Yes, databaseQueueWithPath: takes a path to the database.

For your second question, if you're inserting your data in a background thread and you can break it up in chunks (so the time spent in [queue inDatabase:] ins't very long), then yes, you can still play with the app while that's going on. You won't be able to the various queue methods while one is already in use.

like image 161
ccgus Avatar answered Nov 08 '22 07:11

ccgus