相关这个问题 https://stackoverflow.com/questions/1082554/,我想把数据加载放在后台。
但是,我收到“库例程调用不按顺序”错误。
In 这个所以线程 https://stackoverflow.com/questions/745565/how-to-properly-call-sqlite-functions-from-background-thread-on-iphone说这种方法是使用 NSOperation,但是查看网络上的示例我不知道如何解决该问题。
我与单例模式共享一个 sqlite 连接:
@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;
}
所以打开两次相同的数据库更难......
有任何想法吗?
EDIT:
我确认错误是在调用 sqlite.我使用 FDBM 作为调用它的薄包装器。
我正在运行 2 个线程:主线程和用于加载数据的后台任务。我这样运行:
- (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];
}
数据库接口的代码位于http://code.google.com/p/chibiorm/source/browse/#svn/trunk/src http://code.google.com/p/chibiorm/source/browse/#svn/trunk/src— 特别是 Db.h/m,它是唯一与 fdbm/sqlite 接口的单元。
尝试从 FDBM 调用 sqlite 函数时发生错误。
例如发生在这里:
-(void) checkError {
if ([self.theDb hadError]) { // <====ERROR HERE
NSLog(@"Err %d: %@", [self.theDb lastErrorCode], [self.theDb]);
}
}
这调用了FDBM代码:
- (BOOL) hadError {
int lastErrCode = sqlite3_errcode(db);
return (lastErrCode > SQLITE_OK && lastErrCode < SQLITE_ROW);
}