I have a sync method for an app I'm building storing data in SQLite locally, using the FMDatabase wrapper. When I put all the queries in one class everything works fine. However to maintain complexity I added some data controller classes for parts of the sync, but when I do so FMDatabase gives 'database locked' errors, both when I add a new connection in a data class and when I send along the initial database connection as a parameter.
Now I was thinking to add the database connection in a songleton, and was wondering if that is good practice and how I wrap FMDatabase in a singleton class. Any help on why the issue happens and what's the best way of working around this would be greatly appreciated!
I don't agree with Tumtum's answer. Please read document from FMDB:
You should also consider using FMDatabaseQueue, and stick that in some shared area of your code. It'll be safe to use it on multiple threads as well.
I've implemented a singelton with an FMDatabase using the following code, which seems to have resolved the issue with the locked Database error. Not sure if this is good practice, but here's the code for everyone that needs a similar implementation. I used this tutorial on singeletons.
The singleton:
DatabaseController.h:
DatabaseController.m:
Using the singelton
Then everywhere I need to acces the database I use: