Related to this SO question, I want to put the data loading in the background.
However, I get 'library routine called out of sequence' errors.
In this SO thread say that the way is using NSOperation, but looking on the samples on the web I not know how that could solve the issue.
I share a single sqlite connection with the singleton pattern:
@interface Db : NSObject {
NSString *path;
FMDatabase* theDb;
BOOL isOpen;
}
@property (retain, nonatomic) FMDatabase *theDb;
@property (retain, nonatomic) NSString *path;
@property (nonatomic) BOOL isOpen;
--------
static Db *currentDbSingleton = nil;
#pragma mark Global access
+(id)currentDb {
@synchronized(self) {
if (!currentDbSingleton) {
NSString *reason = NSLocalizedString(@"The database is not set globally",
@"Error Db: database is not set");
NSException *e = [NSException exceptionWithName:@"DBError"
reason:reason;
userInfo:nil];
@throw e;
}
}
return currentDbSingleton;
}
So is harder open twice the same db....
Any ideas?
EDIT:
I confirmed the error is in calling sqlite. I use FDBM as thin wrapper for calling it.
I'm running 2 threads: the main and a background task for loading of the data. I run it this way:
- (void) fillCache:(NSString *)theTable {
[NSThread detachNewThreadSelector:@selector(fillCacheBackground:)
toTarget:self
withObject:theTable];
}
- (void)loadComplete {
[self.table reloadData];
}
- (void) fillCacheBackground:(NSString *)theTable {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
Db *db= [Db currentDb];
[db beginTransaction];
..... STUFF HERE
[db commitTransaction];
//Tell our callback what we've done
[self performSelectorOnMainThread:@selector(loadComplete)
withObject:nil
waitUntilDone:YES];
[pool drain];
}
The code for the db interface is at http://code.google.com/p/chibiorm/source/browse/#svn/trunk/src — specifically the Db.h/m that are the only units that interface with fdbm/sqlite.
The error happend when try to call sqlite functions from FDBM.
For example happend here:
-(void) checkError {
if ([self.theDb hadError]) { // <====ERROR HERE
NSLog(@"Err %d: %@", [self.theDb lastErrorCode], [self.theDb]);
}
}
This call the FDBM code:
- (BOOL) hadError {
int lastErrCode = sqlite3_errcode(db);
return (lastErrCode > SQLITE_OK && lastErrCode < SQLITE_ROW);
}