Using SQLite in your iPhone project means dealing with pure C functions. Fortunately, there are helpful tools wrapping these function in Objective-C objects. FMDB is easy to use and open source so that it could be a perfect solution.
Since Paper Pile starts multiple threads to load new articles and render the newspaper’ pages, database queries may happen at the same time. The FMDB classes pay attention to the fact that only one operation on the database is allowed by “locking” the database.
Every method that forwards the action to SQLite C-functions sets the instance variable inUse to YES after checking that it is NOT YES. After finishing the work the variable gets set back to NO. This way, every instance of FMDatabase can only perform one action. Assuming most apps use a singleton FMDatabase instance, one thread cannot execute SQL statements while another threads is already doing so. By implementation, the second thread’s statement is simply ignored.
There is no easy way to enable real concurrent statement execution. However, we can change the conflict behavior to a way that that every statement gets at least executed.
Simply replace the three occurrences of this code
if (inUse) {
[self compainAboutInUse];
return NO;
}
with this code
while (inUse) {
usleep(50);
}
Now the execution will be paused until the other thread will have finished it execution while the check is performed every 50 milliseconds. Of course, the order of execution is not predictable anymore. However, when using multiple threads dependencies should be handled within the threads anyway.