Share…

FMDB and threaded update/select

FMDB is pretty cool but due to specific iOS behaviour while using threads, it can lead to unexpected results. First rule is – never use FMDB as singleton. Yes, if you’re coming from PHP it can be tempting as single db connection is common there. But consider such scenario:

SELECT myfield FROM mytable WHERE id = 1; // let’s say this will give you “0” as result

User pushed button in your app, which should change “myfield” to 1 and reload data

After this you’re calling something like [self reloadData]; and expected value for “myfield” is “1”, but instead you have still “0”

This happens becouse iOS locked your db and has local “snapshot” in which your “myfield” has value “0”. To prevent this all SELECT/UPDATE/INSERT operations should use FMDatabaseQueue. So your update method should looks like this: